Binary Tree Right Side View

Problem

Given the root of 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.

Example 1:

复制代码
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]

Example 2:

复制代码
Input: root = [1,null,3]
Output: [1,3]

Example 3:

复制代码
Input: root = []
Output: []

Intuition

The task is to imagine standing on the right side of a binary tree and returning the values of the nodes visible from that perspective. The intuition is to perform a level order traversal of the binary tree and, for each level, only consider the value of the rightmost node, as that would be the one visible from the right side.

Approach

Initialization:

Check if the root is None. If so, return an empty list since there are no nodes to traverse.

Breadth-First Search (BFS):

Use a queue (in this case, a deque) to perform a breadth-first traversal of the binary tree.

Initialize the queue with the root node.

Right Side View:

While the queue is not empty:

For each level, create a temporary list (temp) to store the values of nodes.

Process all nodes at the current level:

Pop the front node from the queue.

Enqueue its left and right children (if any).

Append the value of the current node to the temp list.

If the temp list is not empty, append the value of the rightmost node to the final result (stack).

Return Result:

Return the final result, which is a list of values representing the nodes visible from the right side.

Complexity

  • Time complexity:

The time complexity is O(n), where n is the number of nodes in the binary tree. Each node is visited exactly once during the traversal.

  • Space complexity:

The space complexity is O(m), where m is the maximum number of nodes at any level in the binary tree. In the worst case, the maximum number of nodes at any level is the number of leaf nodes, which is at most n/2 in a balanced binary tree. Therefore, the space complexity is O(n/2), which simplifies to O(n) in big-O notation. This is because the space required to store nodes at any level scales with the number of nodes in the tree.

Code

复制代码
# 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]:
        if not root:
            return []

        stack = [root.val]
        q = deque([root])
        while q:
            temp = []
            for _ in range(len(q)):
                node = q.popleft()
                if node.left:
                    q.append(node.left)
                    temp.append(node.left.val)
                if node.right:
                    q.append(node.right)
                    temp.append(node.right.val)

            if temp:
                stack.append(temp[-1])

        return stack
相关推荐
GreenTea7 小时前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
fqq38 小时前
力扣刷题前置Java语法
算法·leetcode·职场和发展
2501_9065651210 小时前
数学之美探究
算法
oier_Asad.Chen10 小时前
【洛谷题解/AcWing题解/OI学习笔记】洛谷P2868【USACO07DEC】Sightseeing Cows G(01分数规划求最大比率)
算法·图论·spfa·二分·负环
leisoo809712 小时前
财报数据怎么排雷本地化Python构建财务异常预警系统
人工智能·python·算法
luj_176814 小时前
塔防牌:策略与卡牌的智慧碰撞
服务器·c语言·开发语言·经验分享·算法
郝学胜-神的一滴15 小时前
干货版《算法导论》17:二叉树核心原理、遍历逻辑与高阶实操全解
数据结构·c++·python·算法·计算机·编程
爱编程的小新☆15 小时前
【LeetCode】从递归到 Flood Fill:5 道题吃透 DFS 的选择、回溯与标记
java·算法·leetcode·深度优先·回溯·flood fill
Water_Sunzhipeng15 小时前
2024牛客暑期多校训练营1
算法
hetao173383715 小时前
2026-08-09~08-14 hetao1733837 的刷题记录
c++·算法