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.
1public class TreeNode {
2 public int val;
3 public TreeNode left;
4 public TreeNode right;
5 public TreeNode(int x) { val = x; }
6}
7public class Solution {
8 public bool 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}
In this C# solution, we define a class TreeNode
and a method IsSameTree
within the Solution
class. The method uses recursion to check if the trees are identical.
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.
1#include <stack>
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 stack<TreeNode*> stackP, stackQ;
6 stackP.push(p);
7 stackQ.push(q);
8 while (!stackP.empty() && !stackQ.empty()) {
9 TreeNode* nodeP = stackP.top(); stackP.pop();
10 TreeNode* nodeQ = stackQ.top(); stackQ.pop();
11 if (!nodeP && !nodeQ) continue;
12 if (!nodeP || !nodeQ || nodeP->val != nodeQ->val) return false;
13 stackP.push(nodeP->right); stackP.push(nodeP->left);
14 stackQ.push(nodeQ->right); stackQ.push(nodeQ->left);
15 }
16 return stackP.empty() && stackQ.empty();
17}
The C++ solution uses a stack from the standard library to iteratively compare tree nodes. The approach mimics tree traversal using stack operations for both trees in tandem.