|
| 1 | +// 🚀 Iterative DFS (Stack) |
| 2 | +// ✅ Time Complexity: O(n), where n is the number of nodes in the tree |
| 3 | +// ✅ Space Complexity: O(n) (worst case), O(log n) (best case for balanced trees) |
| 4 | + |
| 5 | +/** |
| 6 | + * Definition for a binary tree node. |
| 7 | + * function TreeNode(val, left, right) { |
| 8 | + * this.val = (val===undefined ? 0 : val) |
| 9 | + * this.left = (left===undefined ? null : left) |
| 10 | + * this.right = (right===undefined ? null : right) |
| 11 | + * } |
| 12 | + */ |
| 13 | +/** |
| 14 | + * @param {TreeNode} p |
| 15 | + * @param {TreeNode} q |
| 16 | + * @return {boolean} |
| 17 | + */ |
| 18 | +var isSameTree = function (p, q) { |
| 19 | + let stack = [[p, q]]; |
| 20 | + while (stack.length > 0) { |
| 21 | + const [p, q] = stack.pop(); |
| 22 | + |
| 23 | + if (p === null && q === null) continue; |
| 24 | + |
| 25 | + if (p === null || q === null) return false; |
| 26 | + |
| 27 | + if (p.val !== q.val) return false; |
| 28 | + |
| 29 | + stack.push([p.left, q.left]); |
| 30 | + stack.push([p.right, q.right]); |
| 31 | + } |
| 32 | + |
| 33 | + return true; |
| 34 | +}; |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | +// 🚀 recursive approach |
| 39 | +// ✅ Time Complexity: O(n), where n is the number of nodes in the tree |
| 40 | +// ✅ Space Complexity: O(n) (worst case), O(log n) (best case for balanced trees) |
| 41 | + |
| 42 | +/** |
| 43 | + * Definition for a binary tree node. |
| 44 | + * function TreeNode(val, left, right) { |
| 45 | + * this.val = (val===undefined ? 0 : val) |
| 46 | + * this.left = (left===undefined ? null : left) |
| 47 | + * this.right = (right===undefined ? null : right) |
| 48 | + * } |
| 49 | + */ |
| 50 | +/** |
| 51 | + * @param {TreeNode} p |
| 52 | + * @param {TreeNode} q |
| 53 | + * @return {boolean} |
| 54 | + */ |
| 55 | +// var isSameTree = function (p, q) { |
| 56 | +// // Base case: If both trees are empty, they are the same |
| 57 | +// if (p === null && q === null) return true; |
| 58 | + |
| 59 | +// // If one of the trees is empty and the other is not, return false |
| 60 | +// if (p === null || q === null) return false; |
| 61 | + |
| 62 | +// // Compare the values of the current nodes |
| 63 | +// if (p.val !== q.val) return false; |
| 64 | + |
| 65 | +// // Recursively compare the left and right subtrees |
| 66 | +// return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); |
| 67 | +// }; |
| 68 | + |
| 69 | + |
0 commit comments