Leetcode刷题Python199. 二叉树的右视图

Posted Better Bench

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode刷题Python199. 二叉树的右视图相关的知识,希望对你有一定的参考价值。

1 题目

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

示例 1:

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

示例 2:

输入: [1,null,3]
输出: [1,3]

示例 3:

输入: []

2 解析

我们按照 「根结点 -> 右子树 -> 左子树」 的顺序访问, 就可以保证每层都是最先访问最右边的节点的。

3 Python实现

class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        def dfs(node,level):
            if not node:
                return 
            if level ==len(res):
                res.append(node.val)
            # if node.right:
            dfs(node.right,level+1)
            # if node.left:
            dfs(node.left,level+1)
        res = []
        dfs(root,0)
        return res

以上是关于Leetcode刷题Python199. 二叉树的右视图的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode刷题笔记-数据结构-day16

LeetCode刷题笔记-数据结构-day16

Leetcode刷题Python104. 二叉树的最大深度

Leetcode刷题Python94. 二叉树的中序遍历

Leetcode刷题Python145. 二叉树的后序遍历

Leetcode刷题Python144. 二叉树的前序遍历