您的位置:首页 > 编程语言 > Python开发

leetcode-二叉树右视图(python)

2019-03-24 12:21 453 查看

题目:
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例:

输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

1 <—
/
2 3 <—
\
5 4 <—
**思想:**二叉树层次遍历,取出每一层最后一个
代码:

class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if not root:
return []
res=[] #存储最后结果
curnode=[root] #存储当先遍历层数的node
nexnode=[]  #存储下一层的node
res.append(curnode[0].val)

while curnode:
for s in curnode:
if s.right:   #先存储右节点
nexnode.append(s.right)
if s.left:
nexnode.append(s.left)
if nexnode:  #再存储左节点
res.append(nexnode[0].val)
curnode=nexnode
nexnode=[]
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: