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].
class Solution:
# @param root, a tree node
# @return a list of integers
def rightSideView(self, root):
queue1 = []
queue2 = []
last_val_list = []
if(root is None):
return []
queue1.append(root)
while queue1:
root = queue1[0]
if root.left is not None:
queue2.append(root.left)
if root.right is not None:
queue2.append(root.right)
last_val = root.val
del queue1[0]
if queue1 == []:
queue1 = queue2
queue2= []
last_val_list.append(last_val)
return last_val_list
本文介绍如何通过迭代方法实现获取给定二叉树的右视图节点值,从顶层到底层顺序返回可见节点。具体实现包括初始化队列、遍历二叉树并记录每一层的最后一个节点值。
548

被折叠的 条评论
为什么被折叠?



