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.
1import java.util.Stack;
2class TreeNode {
3 int val;
4 TreeNode left;
5 TreeNode right;
6 TreeNode(int x) { val = x; }
7}
8class Solution {
9 public boolean isSameTree(TreeNode p, TreeNode q) {
10 Stack<TreeNode> stackP = new Stack<>();
11 Stack<TreeNode> stackQ = new Stack<>();
12 stackP.push(p);
13 stackQ.push(q);
14 while (!stackP.isEmpty() && !stackQ.isEmpty()) {
15 TreeNode nodeP = stackP.pop();
16 TreeNode nodeQ = stackQ.pop();
17 if (nodeP == null && nodeQ == null) continue;
18 if (nodeP == null || nodeQ == null || nodeP.val != nodeQ.val) return false;
19 stackP.push(nodeP.right);
20 stackP.push(nodeP.left);
21 stackQ.push(nodeQ.right);
22 stackQ.push(nodeQ.left);
23 }
24 return stackP.isEmpty() && stackQ.isEmpty();
25 }
26}
In Java, the iterative approach leverages the stack data structure from the Java Collections framework. Nodes from both trees are compared iteratively, ensuring the structural and value equality of the trees.