Subtree of another tree
Easytreedfsrecursion
Return true if some node in root has a subtree (that node and all its descendants) exactly equal to sub.
Examples write a tree level by level, with null for a missing child: [3,9,20,null,null,15,7].
Example 1
Input: root = [3,4,5,1,2], sub = [4,1,2] Output: true
Example 2
Input: root = [3,4,5,1,2,null,null,null,null,0], sub = [4,1,2] Output: false
There's an extra 0 under the 4, so it isn't an exact match.
Constraints
- 1 ≤ nodes in root ≤ 2000
- 1 ≤ nodes in sub ≤ 1000
- -10⁴ ≤ Node.val ≤ 10⁴
Submit checks your solution against 8 tests, including hidden ones.
// Provided by the judge: keep these definitions
class TreeNode {
constructor(val = 0, left = null, right = null) {
this.val = val
this.left = left
this.right = right
}
}
/**
* @param {TreeNode|null} root
* @param {TreeNode|null} sub
* @return {bool}
*/
function isSubtree(root, sub) {
}