Problem 199

Abstract / Summary

Return the values of the nodes visible from the right side of a binary tree when viewed from top to bottom

Note

The full problem description, including helpful examples, can be found on LeetCode.

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()
12 lines | 358 bytes | submitted September 1, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.15 | σ = 1.43

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
55 links | 38 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Binary Tree Right Side View - Breadth First Search - Leetcode 199'
NeetCode 11 mins
Binary Tree Right Side View - Breadth First Search - Leetcode 199
YouTube video 'Binary Tree Right Side View | BFS | Amazon | Accolite | Flipkart | Live Coding'
codestorywithMIK 11 mins
Binary Tree Right Side View | BFS | Amazon | Accolite | Flipkart | Live Coding
YouTube video 'Binary Tree Right Side View | DFS | Amazon | Leetcode 199'
codestorywithMIK 10 mins
Binary Tree Right Side View | DFS | Amazon | Leetcode 199
YouTube video 'Binary Tree Right Side View - LeetCode 199 Python'
Deepti Talesra 9 mins
Binary Tree Right Side View - LeetCode 199 Python
YouTube video 'Binary Tree Right Side View (LeetCode 199) | Both Views with the thought process'
Nikhil Lohia 12 mins
Binary Tree Right Side View (LeetCode 199) | Both Views with the thought process
YouTube video 'BINARY TREE RIGHT SIDE VIEW | PYTHON SOLUTION | LEETCODE # 199'
Cracking FAANG 6 mins
BINARY TREE RIGHT SIDE VIEW | PYTHON SOLUTION | LEETCODE # 199
YouTube video 'Binary Tree Right Side View | Leetcode 199 | Binary Tree'
Ayushi Sharma 16 mins
Binary Tree Right Side View | Leetcode 199 | Binary Tree
YouTube video 'Binary Tree Right Side View || Leetcode 199 || 2 Variants Big Tech Asks'
Coding with Minmer 27 mins
Binary Tree Right Side View || Leetcode 199 || 2 Variants Big Tech Asks
YouTube video 'Binary Tree Right Side View || Binary Tree Left Side view || With code || Interview Problem'
code Explainer 9 mins
Binary Tree Right Side View || Binary Tree Left Side view || With code || Interview Problem
YouTube video 'Solving LeetCode 199 in JavaScript (Binary Tree Right Side View)'
KA Education 6 mins
Solving LeetCode 199 in JavaScript (Binary Tree Right Side View)
YouTube video 'Binary Tree Right Side View | LeetCode 199 | BFS | DFS Tree | Facebook | Amazon | Microsoft'
Naresh Gupta 10 mins
Binary Tree Right Side View | LeetCode 199 | BFS | DFS Tree | Facebook | Amazon | Microsoft
YouTube video 'Binary Tree Right Side View - LeetCode 199 - JavaScript'
AlgoJS 5 mins
Binary Tree Right Side View - LeetCode 199 - JavaScript
YouTube video 'Leetcode | 199. Binary Tree Right Side View | Medium | Java [BFS Solution]'
Developer Docs 7 mins
Leetcode | 199. Binary Tree Right Side View | Medium | Java [BFS Solution]
YouTube video 'Binary Tree Right Side View | Leetcode 199'
Coding Decoded 8 mins
Binary Tree Right Side View | Leetcode 199
YouTube video 'Apple Coding Interview Question | Leetcode 199 | Binary Tree Right Side View'
WorkWithGoogler 13 mins
Apple Coding Interview Question | Leetcode 199 | Binary Tree Right Side View
YouTube video 'Daily Leetcode #832: Jul 11, 2022 - 199. Binary Tree Right Side View'
Programming Live with Larry 7 mins
Daily Leetcode #832: Jul 11, 2022 - 199. Binary Tree Right Side View
YouTube video 'Leetcode 199: Binary Tree Right Side View'
Algorithms Casts 20 mins
Leetcode 199: Binary Tree Right Side View
YouTube video 'Leetcode - 199 | Binary Tree Right Side View | Pirai's Academy | Half Moon Coder.'
Pirai's Academy 3 mins
Leetcode - 199 | Binary Tree Right Side View | Pirai's Academy | Half Moon Coder.
YouTube video '199. Binary Tree Right Side View | Leetcode | Binary Tree | DSA'
Coding with Tamilarasan 22 mins
199. Binary Tree Right Side View | Leetcode | Binary Tree | DSA
YouTube video 'Daily Leetcode #312: Feb 06, 2021 - 199. Binary Tree Right Side View'
Programming Live with Larry 8 mins
Daily Leetcode #312: Feb 06, 2021 - 199. Binary Tree Right Side View
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

30 solutions   September 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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