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.
1#include <iostream>
2using namespace std;
3struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} };
4bool isSameTree(TreeNode* p, TreeNode* q) {
5 if (!p && !q) return true;
6 if (!p || !q) return false;
7 return (p->val == q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
8}
The solution in C++ is similar to C. We define a struct for the TreeNode and use a recursive function isSameTree
that checks if two trees are identical by comparing the root values and recursively checking the left and right subtrees.
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.