Description
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.
输出最右侧的那一列
Solution
很巧妙的方法使用post-order 遍历记录下一层第一个非None的node
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
# write your code here
def collect(node, depth):
if node:
if depth == len(view):
view.append(node.val)
collect(node.right, depth + 1)
collect(node.left, depth + 1)
view = []
collect(root, 0)
return view
网友评论