LeetCode 题解工作台

二叉树的右视图

给定一个二叉树的 根节点 root ,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。 示例 1: 输入: root = [1,2,3,null,5,null,4] 输出: [1,3,4] 解释: 示例 2: 输入: root = [1,2,3,4,null,null,nu…

category

4

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

我们可以使用广度优先搜索,定义一个队列 ,将根节点放入队列中。每次从队列中取出当前层的所有节点,对于当前节点,我们先判断右子树是否存在,若存在则将右子树放入队列中;再判断左子树是否存在,若存在则将左子树放入队列中。这样每次取出队列中的第一个节点即为该层的右视图节点。 时间复杂度 ,空间复杂度 。其中 为二叉树节点个数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

 

示例 1:

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

输出:[1,3,4]

解释:

示例 2:

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

输出:[1,3,4,5]

解释:

示例 3:

输入:root = [1,null,3]

输出:[1,3]

示例 4:

输入:root = []

输出:[]

 

提示:

  • 二叉树的节点个数的范围是 [0,100]
  • -100 <= Node.val <= 100 
lightbulb

解题思路

方法一:BFS

我们可以使用广度优先搜索,定义一个队列 q\textit{q},将根节点放入队列中。每次从队列中取出当前层的所有节点,对于当前节点,我们先判断右子树是否存在,若存在则将右子树放入队列中;再判断左子树是否存在,若存在则将左子树放入队列中。这样每次取出队列中的第一个节点即为该层的右视图节点。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为二叉树节点个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        ans = []
        if root is None:
            return ans
        q = deque([root])
        while q:
            ans.append(q[0].val)
            for _ in range(len(q)):
                node = q.popleft()
                if node.right:
                    q.append(node.right)
                if node.left:
                    q.append(node.left)
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Can the candidate explain the difference in approach between BFS and DFS for this problem?

  • question_mark

    Does the candidate understand the importance of tracking the rightmost nodes?

  • question_mark

    Does the candidate optimize space by choosing the appropriate traversal strategy for the tree's shape?

warning

常见陷阱

外企场景
  • error

    Confusing the BFS and DFS traversal methods or not choosing the optimal one for the problem's constraints.

  • error

    Failing to account for the edge case of an empty tree or ensuring the correct handling of null nodes.

  • error

    Incorrectly managing the state during traversal, leading to missing or extra nodes in the output.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the tree is extremely unbalanced? Can you still solve it efficiently?

  • arrow_right_alt

    How does the solution change if you need to return the left side view instead of the right?

  • arrow_right_alt

    Can you solve the problem without using recursion?

help

常见问题

外企场景

二叉树的右视图题解:二分·树·traversal | LeetCode #199 中等