[
tree
bfs
dfs
recursion
]
Leetcode 0199. Binary Tree Right Side View
https://leetcode.com/problems/binary-tree-right-side-view
Like in many other problems about binary trees, we need to somehow traverse our tree, using dfs (inorder, preorder or postorder) or bfs. There are different solutions here, I use almost inorder traversal, with just one small change: instead of going Left -> Node -> Right
, we will go Right -> Node -> Left
. In this way we first visit nodes on the right side of our tree. Algorithm will look like this:
- Create
ans
dictionary, which for each levelH
will keep the rightest node. - Traverse tree: first visit right children and if we do not have this
H
inans
yet, we put it there, then visit left children. Note again that with this order of traversal we always will put the rightest node for each level and next time we visit this level we will do nothing. - Finally, create list from our dictionary.
Complexity: time complexity is O(n)
for classical dfs, space is O(h)
, again classical complexity for dfs as well as this amount of space we need to keep in our answer.
class Solution:
def rightSideView(self, root):
ans = {}
def dfs(node, H):
if not node: return
dfs(node.right, H + 1)
if H not in ans: ans[H] = node.val
dfs(node.left, H + 1)
dfs(root, 0)
return [ans[i] for i in range(len(ans))]
If you like the solution, you can upvote it on leetcode discussion section: Problem 0199