EASY NC#51 Blind #66 Trees
572. Subtree of Another Tree
📖 Problem
Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot, and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.
🧠 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
- •In-place array updates
- •Sorted array traversal
- •Boundary condition checks
Logical Thinking Concepts
- •Define invariants before coding
- •Check edge cases first (`[]`, single element, duplicates)
- •Estimate time/space before implementation
- •Apply Two Pointers reasoning pattern
- •Apply BFS reasoning pattern
- •Apply Recursion reasoning pattern
💡 Approach
- → For each node in root, check if it matches subRoot
- → Use isSameTree helper to compare two trees
- → Recursively check left and right subtrees
- → Time: O(m * n) where m = nodes in root, n = nodes in subRoot
🛠️ Hints & Pitfalls
Hints
- •For each node in root, check if it matches subRoot
- •Use isSameTree helper to compare two trees
- •Recursively check left and right subtrees
Common Pitfalls
- •Time: O(m * n) where m = nodes in root, n = nodes in subRoot
🧪 Test Cases
Hidden tests on submit: 3
Test Case 1
Not run Input:
buildTree([3,4,5,1,2]); Expected:
{"val":3,"left":{"val":4,"left":{"val":1,"left":null,"right":null},"right":{"val":2,"left":null,"right":null}},"right":{"val":5,"left":null,"right":null}} Test Case 2
Not run Input:
buildTree([4,1,2]); Expected:
{"val":4,"left":{"val":1,"left":null,"right":null},"right":{"val":2,"left":null,"right":null}} Test Case 3
Not run Input:
buildTree([4,1,2,1]); Expected:
{"val":4,"left":{"val":1,"left":{"val":1,"left":null,"right":null},"right":null},"right":{"val":2,"left":null,"right":null}} 📝 Code Editor
📤 Output