leetcode-199题:binary tree right side view

题目: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].

思路:其实就是按层次遍历,保留每层的最右边的结点

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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