This approach involves recursively checking each node of the trees. You start at the roots and compare their values. If they are the same, you proceed to check their left and right subtrees. If at any point the checks fail (either structure or node values don't match), you conclude that the trees are not identical.
The time complexity of this approach is O(N), where N is the total number of nodes in the trees, since each node is visited once. The space complexity is O(H) for the recursion stack, where H is the height of the trees.
1function TreeNode(val, left = null, right = null) {
2 this.val = (val===undefined ? 0 : val);
3 this.left = (left===undefined ? null : left);
4 this.right = (right===undefined ? null : right);
5}
6var isSameTree = function(p, q) {
7 if (!p && !q) return true;
8 if (!p || !q) return false;
9 return (p.val === q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
10};
In JavaScript, the TreeNode function is used to create nodes, and a function isSameTree
is defined to recursively check for tree equality by comparing each node's value and children structural similarity.
This approach involves using a stack to iteratively check whether two trees are identical. You use a stack to simulate the recursive process, always working on node pairs from both trees. For every processed pair, check for value equality, then push their children into the stack to process afterwards (with left and right children being compared correspondingly).
The time complexity remains O(N) since each node is processed exactly once. Space complexity could also be up to O(H) for the stack usage, being the tree's height.
1function TreeNode(val, left = null, right = null) {
2 this.val = (val===undefined ? 0 : val);
3 this.left = (left===undefined ? null : left);
4 this.right = (right===undefined ? null : right);
5}
6var isSameTree = function(p, q) {
7 let stackP = [p], stackQ = [q];
8 while (stackP.length && stackQ.length) {
9 let nodeP = stackP.pop();
10 let nodeQ = stackQ.pop();
11 if (!nodeP && !nodeQ) continue;
12 if (!nodeP || !nodeQ || nodeP.val !== nodeQ.val) return false;
13 stackP.push(nodeP.right);
14 stackP.push(nodeP.left);
15 stackQ.push(nodeQ.right);
16 stackQ.push(nodeQ.left);
17 }
18 return stackP.length === 0 && stackQ.length === 0;
19};
Using an array as a stack in JavaScript, this solution checks the equality of nodes in both trees iteratively. The stack enables node-by-node comparisons while managing their children for subsequent evaluation.