dfs
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.res = []
def pre(root,depth):
if not root:
return
if depth == len(self.res):
self.res.append(root.val)
depth += 1
pre(root.right,depth)
pre(root.left,depth)
pre(root,0)
return self.res
bfs
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
stack = [root]
if not root:
return res
while stack:
lenth = len(stack)
for i in range(lenth):
x = stack.pop(0)
if x.left:
stack.append(x.left)
if x.right:
stack.append(x.right)
if i == lenth-1:
res.append(x.val)
return res