|
| 1 | +/** |
| 2 | + * https://leetcode.com/problems/subtree-of-another-tree/description/ |
| 3 | + * Definition for a binary tree node. |
| 4 | + * function TreeNode(val, left, right) { |
| 5 | + * this.val = (val===undefined ? 0 : val) |
| 6 | + * this.left = (left===undefined ? null : left) |
| 7 | + * this.right = (right===undefined ? null : right) |
| 8 | + * } |
| 9 | + */ |
| 10 | +/** |
| 11 | + * @param {TreeNode} root |
| 12 | + * @param {TreeNode} subRoot |
| 13 | + * @return {boolean} |
| 14 | + */ |
| 15 | +var isSubtree = function (root, subRoot) { |
| 16 | + // If the main tree is empty, it can't contain subRoot |
| 17 | + if (!root) return false; |
| 18 | + |
| 19 | + // If the trees rooted at current node are the same, return true |
| 20 | + if (isSameTree(root, subRoot)) { |
| 21 | + return true; |
| 22 | + } |
| 23 | + |
| 24 | + // Otherwise, recursively check left and right subtrees |
| 25 | + return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); |
| 26 | +}; |
| 27 | + |
| 28 | +function isSameTree(s, t) { |
| 29 | + // If both nodes are null, trees are identical at this branch |
| 30 | + if (!s && !t) return true; |
| 31 | + |
| 32 | + // If only one is null, trees are not identical |
| 33 | + if (!s || !t) return false; |
| 34 | + |
| 35 | + // If current node values are different, trees are not identical |
| 36 | + if (s.val !== t.val) return false; |
| 37 | + |
| 38 | + // Recursively check left and right children |
| 39 | + return isSameTree(s.left, t.left) && isSameTree(s.right, t.right); |
| 40 | +} |
0 commit comments