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 <stdbool.h>
2typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode;
3bool isSameTree(TreeNode* p, TreeNode* q) {
4 if (!p && !q) return true;
5 if (!p || !q) return false;
6 return (p->val == q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
7}
We define a recursive function isSameTree
which takes two tree nodes as parameters. It first checks if both nodes are null, returning true
if they are. If one of them is null, it returns false
. If neither is null, it compares their values and recursively checks their left and right children.
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 <stdbool.h>
2#include <stdlib.h>
3#include "stack.h"
4typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode;
5bool isSameTree(TreeNode* p, TreeNode* q) {
6 Stack *stackP = createStack();
7 Stack *stackQ = createStack();
8 push(stackP, p);
9 push(stackQ, q);
10 while (!isEmpty(stackP) && !isEmpty(stackQ)) {
11 TreeNode* nodeP = pop(stackP);
12 TreeNode* nodeQ = pop(stackQ);
13 if (!nodeP && !nodeQ) continue;
14 if (!nodeP || !nodeQ || nodeP->val != nodeQ->val) return false;
15 push(stackP, nodeP->left);
16 push(stackP, nodeP->right);
17 push(stackQ, nodeQ->left);
18 push(stackQ, nodeQ->right);
19 }
20 return isEmpty(stackP) && isEmpty(stackQ);
21}
Here we use a custom stack (assume it's implemented in the included 'stack.h') to iteratively check both trees' nodes in an iterative fashion. Nodes from both trees are pushed onto the corresponding stacks and checked for equality in pairs.