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.
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7def isSameTree(p, q):
8 if not p and not q:
9 return True
10 if not p or not q:
11 return False
12 return (p.val == q.val) and isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
The Python version of the solution defines a TreeNode class and implements the isSameTree
function to recursively compare the trees starting from the root node, evaluating each node's value and subtree structure.
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.