美文网首页
[**Med DFS]199. Binary Tree Righ

[**Med DFS]199. Binary Tree Righ

作者: Mree111 | 来源:发表于2019-10-17 13:14 被阅读0次

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

相关文章

网友评论

      本文标题:[**Med DFS]199. Binary Tree Righ

      本文链接:https://www.haomeiwen.com/subject/wovmmctx.html