您的位置:首页 > 其它

【LEETCODE】199-Binary Tree Right Side View

2015-11-05 21:27 309 查看
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].

# 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]
"""

if root is None:
return []

result=[]
cur=[root]

while cur:
nextlevel=[]                            #存放下一层的node
for i,node in enumerate(cur):           #当前层的 所有节点node 和其序号
if node.left:
nextlevel.append(node.left)      #nextlevel先记录left child,再记录right child
if node.right:
nextlevel.append(node.right)
if i==len(cur)-1:                   #如果当前node就是当前层的最右点,则append到result里
result.append(node.val)
cur=nextlevel                           #循环完当前层的node后,cur进入下一层
return result
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: