Python 0199.py
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
right = { }
def deeper(node, depth):
if node:
right[depth] = node.val
deeper(node.left, depth + 1)
deeper(node.right, depth + 1)
deeper(root, 0)
return right.values()
Difficulty
and has an acceptance rate of about 71% (3+ million submissions).
Typical patterns to solve this problem:
- Binary Tree
- Breadth First Search
- Depth First Search
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a method rightSideView that returns the values of the nodes visible when a binary tree is observed from the right side. The algorithm uses a depth-first traversal to record the most recent node encountered at each depth, ultimately producing a collection of right-most values.
Key Steps
The method begins by creating an empty dictionary named right. This dictionary maps each depth level to the node value that was last visited at that depth.
right = { }
A nested helper function called deeper is defined to perform the recursive traversal. The function accepts a node and its corresponding depth. If the node exists, its value overwrites any previous entry for that depth in the right dictionary, ensuring that the most recent node at that level is retained.
def deeper(node, depth):
if node:
right[depth] = node.val
deeper(node.left, depth + 1)
deeper(node.right, depth + 1)
The traversal order is left child first, then right child. Because the dictionary entry for a depth is overwritten each time a node at that depth is visited, the final value stored for each depth corresponds to the rightmost node encountered during the depth-first walk.
The recursion is initiated with the root node at depth 0.
deeper(root, 0)
After the entire tree has been explored, the method returns the collection of values stored in the dictionary, preserving the order of insertion which reflects increasing depth.
return right.values()
Edge Cases Handled
When the input root is None, the helper function receives a None node at depth 0. The conditional if node: prevents any further processing, leaving the right dictionary empty. Consequently, the method returns an empty view, correctly representing the absence of visible nodes.
If the tree consists of a single node, the recursion records that node at depth 0 and then terminates, resulting in a view containing exactly that one value.
For highly unbalanced trees, such as those that extend only to the left or only to the right, the depth-first approach still visits every node. In a left-leaning tree, each depth is overwritten by the leftmost node, which is also the rightmost visible node because no right sibling exists. In a right-leaning tree, each depth is overwritten by the rightmost node, matching the expected right-side view.
The algorithm also gracefully handles trees with duplicate values. Since the dictionary keys are depths, not node values, each depth stores the most recent node encountered regardless of value duplication, ensuring the correct structural view is produced.
Performance Optimizations
The use of a dictionary keyed by depth eliminates the need for an auxiliary list or queue to track nodes at each level. By overwriting the entry for a depth whenever a new node at that depth is visited, the algorithm automatically retains only the last (rightmost) node without additional comparisons.
Recursion provides a natural stack-based traversal, avoiding explicit data structures such as stacks or deques. This reduces overhead and leverages Python’s call stack for depth management.
Returning right.values() directly yields a view object that reflects the insertion order of depths, avoiding an extra copy or sorting step. This leverages the ordered nature of dictionaries in modern Python implementations to produce the final result efficiently.
ELI5 - Simplified Explanation
Imagine a tree made of branches that instead of growing up, grow down towards the floor. At the very top, there is one main branch, and from there, it splits into more branches, and those split into even more. This code is like a little robot standing to the right side of this tree looking at it.
The robot wants to make a list of the nodes it can see when standing on the right. Since it is standing on the side, it looks at each level of the tree. If it sees a branch on a level, it remembers it. If it sees another branch on that same level, it replaces the old one with the new one because the new one is further to the right.
To do this, the code starts at the top and goes down the branches one by one. It keeps a notebook to write down the name of the branch it sees at each depth. It visits the left side first and then the right side. Because it updates the notebook whenever it finds a new branch at the same depth, by the time it finishes looking at the whole tree, the notebook only has the branches that were furthest to the right at every level. The robot just reads through its notebook to tell everyone what it saw.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | JS | Java | Rust | TS | Go | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python | |||||||||||
| bujosa | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| DimitrisJim | JS | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | TS | ||||||||||
| MacJim | C++ | |||||||||||
| ruoru | Rust | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python, Python | |||||||||||
| bujosa | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| DimitrisJim | JavaScript | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++, TypeScript | |||||||||||
| MacJim | C++ | |||||||||||
| ruoru | Rust | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 116: Populating Next Right Pointers in Each Node
- problem 545: Boundary of Binary Tree
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 222: Count Complete Tree Nodes
- problem 404: Sum of Left Leaves
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 79: Word Search
- problem 81: Search in Rotated Sorted Array II
- problem 97: Interleaving String
- problem 99: Recover Binary Search Tree
- problem 173: Binary Search Tree Iterator
- problem 230: Kth Smallest Element in a BST
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 508: Most Frequent Subtree Sum
- problem 513: Find Bottom Left Tree Value
- problem 538: Convert BST to Greater Tree
- problem 65: Valid Number
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
- problem 127: Word Ladder
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality