if len(res)<=depth
时, 说明遍历到了该层第一个元素,这时加个0用来占位置(第depth层的元素)- 先深度遍历左子树,再深度遍历右子树,这样,这一层的值会被每一层的最后一个节点最终覆盖掉。用这种方式来实现右视图
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res=[]
def dfs(root,depth):
if not root:
return res
if len(res)<=depth:
res.append(0)
res[depth]=root.val
dfs(root.left,depth+1)
dfs(root.right,depth+1)
dfs(root,0)
return res