Command Palette
Search for a command to run...
Problem 16.3 · Binary TreesEasy
What it teaches: Recurse on two trees at once, comparing structure and values.
Practise it on judges as “Same Tree”.
The problem
Return true if two binary trees have the same structure and the same values at every node.
Example 1
Input: p = [1, 2, 3], q = [1, 2, 3]
Output: true
Example 2
Input: p = [1, 2], q = [1, null, 2]
Output: false
Constraints
Pattern clues in the wording
- → Two trees walked in lockstep
These clues point to Tree DFS: Recurse into the left and right children and combine what they return (height, sums, paths).
Stuck? Take one hint at a time
Solution.java · starterclass Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
return false;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Test cases
| # | Input | Expected |
|---|
| 1 | p = [1,2,3] q = [1,2,3] | true |
| 2 | p = [1,2] q = [1,null,2] | false |
| 3 | p = [1,2,1] q = [1,1,2] | false |
+ 1 hidden test the code runner will check