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 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode(int x) { val = x; }
6}
7class Solution {
8 public boolean isSameTree(TreeNode p, TreeNode q) {
9 if (p == null && q == null) return true;
10 if (p == null || q == null) return false;
11 return (p.val == q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
12 }
13}
This Java solution involves defining the TreeNode class and using a method isSameTree
within the Solution class to recursively determine if two trees are the same by comparing their nodes' values and their children's trees.
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.