MEDIUM NC#54 Trees
199. Binary Tree Right Side View
๐ Problem
Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
๐ง 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
๐ก Approach
- โ Use level order traversal (BFS)
- โ For each level, take the rightmost node
- โ Collect these rightmost nodes' values
- โ Time: O(n), Space: O(w) where w is max width
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse level order traversal (BFS)
- โขFor each level, take the rightmost node
- โขCollect these rightmost nodes' values
Common Pitfalls
- โขTime: O(n), Space: O(w) where w is max width
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
rightSideView(buildTree([1,2,3,null,5,null,4])); Expected:
[1, 3, 4] Test Case 2
Not run Input:
rightSideView(buildTree([1,null,3])); Expected:
[1, 3] Test Case 3
Not run Input:
rightSideView(buildTree([])); Expected:
[] ๐ Code Editor
๐ค Output