Same Tree Visualizer & Step-by-Step Algorithm Solution

Check if two binary trees are structurally identical and have the same node values using simultaneous DFS recursion.

Category: trees | Difficulty: Easy

Tags: DFS, Binary Tree, Recursion, Tree Comparison

Same Tree

1
2
3
1
2
3
100%
state
resultcomparing
Initialization
1/22
Explanation

Start isSameTree comparing Tree P and Tree Q.

Source Code
1function isSameTree(p, q) {
2 if (!p && !q) return true;
3 if (!p || !q) return false;
4 if (p.val !== q.val) return false;
5 return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
6}