|
| 1 | +function TreeNode(val, left, right) { |
| 2 | + this.val = val === undefined ? 0 : val; |
| 3 | + this.left = left === undefined ? null : left; |
| 4 | + this.right = right === undefined ? null : right; |
| 5 | +} |
| 6 | + |
| 7 | +/** |
| 8 | + * @param {TreeNode} p |
| 9 | + * @param {TreeNode} q |
| 10 | + * @return {boolean} |
| 11 | + */ |
| 12 | +var isSameTree = function (p, q) { |
| 13 | + if (!p && !q) { |
| 14 | + return true; |
| 15 | + } |
| 16 | + |
| 17 | + if (!p || !q || p.val !== q.val) { |
| 18 | + return false; |
| 19 | + } |
| 20 | + |
| 21 | + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); |
| 22 | +}; |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {TreeNode} root |
| 26 | + * @param {TreeNode} subRoot |
| 27 | + * @return {boolean} |
| 28 | + */ |
| 29 | +var isSubtree = function (root, subRoot) { |
| 30 | + if (subRoot === null) { |
| 31 | + return true; |
| 32 | + } |
| 33 | + |
| 34 | + if (root === null && subRoot !== null) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + |
| 38 | + if (isSameTree(root, subRoot)) { |
| 39 | + return true; |
| 40 | + } |
| 41 | + |
| 42 | + return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); |
| 43 | +}; |
| 44 | + |
| 45 | +/** |
| 46 | + * Time Complexity: O(n * m), n: number of nodes in tree `subRoot`, m: number of nodes in tree `root` |
| 47 | + * Reason: |
| 48 | + * The `isSameTree` function is called at every node of tree `root`. |
| 49 | + * The time complexity of the `isSameTree` function is O(n) since it compares all nodes of the two trees, |
| 50 | + * where n is the number of nodes in tree `subRoot`. |
| 51 | + * |
| 52 | + * Since `isSameTree` is called at every node of tree `root`, |
| 53 | + * the worst-case time complexity is O(n * m), |
| 54 | + * where m is the number of nodes in tree `root`. |
| 55 | + */ |
| 56 | + |
| 57 | +/** |
| 58 | + * Space Complexity: O(h), where h is the height of tree `root` |
| 59 | + * Reason: |
| 60 | + * The space complexity is determined by the depth of the recursion stack. |
| 61 | + * In the worst case, the recursion will reach the maximum depth of tree `root`, which is its height h. |
| 62 | + * Therefore, the space complexity is O(h). |
| 63 | + */ |
0 commit comments