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

[和小菜鸡一起刷题(python)] LeetCode 199. 二叉树的右视图. (Binary Tree Right Side View)

2019-03-22 11:26 796 查看

LeetCode 199. 二叉树的右视图(Binary Tree Right Side View)

原题

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

示例:

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

1            <---
/   \
2     3         <---
\     \
5     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 not root: return []
res = []
p1 = [root]
while p1:
res.append(p1[-1].val)
p = []
for node in p1:
if node.left: p.append(node.left)
if node.right: p.append(node.right)
p1 = p
return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: