LeetCode 题解工作台
二叉树的右视图
给定一个二叉树的 根节点 root ,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。 示例 1: 输入: root = [1,2,3,null,5,null,4] 输出: [1,3,4] 解释: 示例 2: 输入: root = [1,2,3,4,null,null,nu…
4
题型
7
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
我们可以使用广度优先搜索,定义一个队列 ,将根节点放入队列中。每次从队列中取出当前层的所有节点,对于当前节点,我们先判断右子树是否存在,若存在则将右子树放入队列中;再判断左子树是否存在,若存在则将左子树放入队列中。这样每次取出队列中的第一个节点即为该层的右视图节点。 时间复杂度 ,空间复杂度 。其中 为二叉树节点个数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给定一个二叉树的 根节点 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
解题思路
方法一:BFS
我们可以使用广度优先搜索,定义一个队列 ,将根节点放入队列中。每次从队列中取出当前层的所有节点,对于当前节点,我们先判断右子树是否存在,若存在则将右子树放入队列中;再判断左子树是否存在,若存在则将左子树放入队列中。这样每次取出队列中的第一个节点即为该层的右视图节点。
时间复杂度 ,空间复杂度 。其中 为二叉树节点个数。
# 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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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?
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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?