LeetCode 199. Binary Tree Right Side View
考点 | 难度 |
---|---|
DFS | Medium |
题目
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.
思路
先traverse right child并且用dictionary记录level数和最右边的node
答案
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))]