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.
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 if (!p && !q) return true;
8 if (!p || !q) return false;
9 return (p.val === q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
10};
In JavaScript, the TreeNode function is used to create nodes, and a function isSameTree
is defined to recursively check for tree equality by comparing each node's value and children structural similarity.
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.