Same Tree
Problem Statement
Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Constraints:
- The number of nodes in both trees is in the range [0, 100]
- -10^4 <= Node.val <= 10^4
Input Format:
- Two binary tree roots p and q
Output Format:
- Return true if the trees are the same, false otherwise.
Examples:
Example 1:
Input:
p = [1,2,3], q = [1,2,3]
Output:
true
Explanation:
Both trees have the same structure and node values.
Example 2:
Input:
p = [1,2], q = [1,null,2]
Output:
false
Explanation:
The trees have different structures.
Example 3:
Input:
p = [1,2,1], q = [1,1,2]
Output:
false
Explanation:
The trees have the same structure but different node values.
Solutions
Recursive DFS Approach
Use recursion to check if both trees have identical structure and values.
Iterative BFS Approach
Use a queue to perform a breadth-first traversal of both trees simultaneously.
Algorithm Walkthrough
Example input: nums = []
Step-by-step execution:
- Check if the root nodes are both null: false
- Check if one root node is null: false
- Compare root values: 1 == 1, continue
- Check left subtrees recursively:
- p.left = 2, q.left = 2, values are the same
- p.left.left = null, q.left.left = null, continue
- p.left.right = null, q.left.right = null, continue
- Check right subtrees recursively:
- p.right = 3, q.right = 3, values are the same
- p.right.left = null, q.right.left = null, continue
- p.right.right = null, q.right.right = null, continue
- All nodes match, return true
Hints
Hint 1
Hint 2
Hint 3
Video Tutorial
Video tutorials can be a great way to understand algorithms visually
Visualization
Visualize the traversal of both binary trees simultaneously, highlighting the matching and non-matching nodes.
Key visualization elements:
- current node 1
- current node 2
- comparison result
Implementation Notes
This is a foundational binary tree problem that tests understanding of tree traversal and comparison. It's an excellent introduction to recursive DFS on trees.