题目:Given 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.
For example:
Given the following binary tree,
1 <---
/
2 3 <---
\
5 4 <---
You should return [1, 3, 4].
思路:其实就是按层次遍历,保留每层的最右边的结点
代码:
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result = []
if root == None:
return result
queue = [root,'#']
tag = True
while len(queue) != 1:
node = queue[0]
queue.remove(node)
if node == '#':
tag = True
queue.append('#')
else:
if node.right != None:
queue.append(node.right)
if node.left != None:
queue.append(node.left)
if tag:
result.append(node.val)
tag = False
return result
网友评论