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
相关推荐
2601_954526754 小时前
【工业传感与算法实战】温漂补偿与零点抗漂破局:基于二阶多项式拟合的 C/C++ 边缘校准算法,深度拆解“压力变送器什么牌子好”的技术硬指标
c语言·c++·算法
叩码以求索5 小时前
浅谈:算法萌新如何高效刷题应对面试(一)
算法·面试·职场和发展
c238566 小时前
把 C++ 内存分配拆透:new 与 malloc 的三层血缘
开发语言·c++·算法
aaaameliaaa7 小时前
指针之总结
c语言·笔记·算法
宵时待雨8 小时前
优选算法专题9:哈希表
数据结构·算法·散列表
txzrxz8 小时前
最短路问题——Dijkstra 算法
数据结构·c++·算法·最短路·优先队列
gwf2168 小时前
磨损均衡算法(Wear Leveling)——SSD如何让每块闪存“公平退休“?
运维·数据库·人工智能·python·嵌入式硬件·算法·智能硬件
noipp8 小时前
推荐题目:洛谷 P6231 [JSOI2013] 公交系统
c语言·数据结构·c++·算法·游戏·洛谷·luogu
c238568 小时前
C/C++每日一练6
c语言·c++·算法
AI小码9 小时前
把动作「画」给视频世界模型,跨本体双向推演,李飞飞参与
大数据·人工智能·算法·ai·大模型·音视频·编程