EASY NC#50 Blind #61 Trees
100. Same Tree
๐ Problem
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.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขLevel-order traversal
- โขQueue discipline
- โขShortest-step interpretation
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply BFS reasoning pattern
- โขApply Recursion reasoning pattern
๐ก Approach
- โ Use recursive approach to compare corresponding nodes
- โ Base case: both null (same), one null (different)
- โ Compare values and recursively check both subtrees
- โ Time: O(min(m, n)), Space: O(h) where h is tree height
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse recursive approach to compare corresponding nodes
- โขBase case: both null (same), one null (different)
- โขCompare values and recursively check both subtrees
Common Pitfalls
- โขTime: O(min(m, n)), Space: O(h) where h is tree height
๐งช Test Cases
Hidden tests on submit: 3
Test Case 1
Not run Input:
buildTree([1,2,3]); Expected:
{"val":1,"left":{"val":2,"left":null,"right":null},"right":{"val":3,"left":null,"right":null}} Test Case 2
Not run Input:
buildTree([1,2]); Expected:
{"val":1,"left":{"val":2,"left":null,"right":null},"right":null} Test Case 3
Not run Input:
buildTree([1,null,2]); Expected:
{"val":1,"left":null,"right":{"val":2,"left":null,"right":null}} ๐ Code Editor
๐ค Output