LeetCode-199. 二叉树的右视图【树 深度优先搜索 广度优先搜索 二叉树】

LeetCode-199. 二叉树的右视图【树 深度优先搜索 广度优先搜索 二叉树】

题目描述:

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

示例 1:

输入: 1,2,3,null,5,null,4

输出: 1,3,4

示例 2:

输入: 1,null,3

输出: 1,3

示例 3:

输入: \[\]

输出: \[\]

提示:

二叉树的节点个数的范围是 0,100

-100 <= Node.val <= 100

解题思路一:广度优先搜索

我们可以对二叉树进行层次遍历,那么对于每层来说,最右边的结点一定是最后被遍历到的。二叉树的层次遍历可以用广度优先搜索实现。

python 复制代码
# 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 []
        queue = collections.deque([root])
        result = []
        while queue:
            sz = len(queue)
            for i in range(sz):
                cur = queue.popleft()
                if i == sz - 1:
                    result.append(cur.val)
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
        return result

时间复杂度:O(n)

空间复杂度:O(n)

解题思路二:深度优先搜索

我们对树进行深度优先搜索,在搜索过程中,我们总是先访问右子树。那么对于每一层来说,我们在这层见到的第一个结点一定是最右边的结点。

python 复制代码
class Solution:
    def rightSideView(self, root: TreeNode) -> List[int]:
        rightmost_value_at_depth = dict() # 深度为索引,存放节点的值
        max_depth = -1

        stack = [(root, 0)]
        while stack:
            node, depth = stack.pop()

            if node is not None:
                # 维护二叉树的最大深度
                max_depth = max(max_depth, depth)

                # 如果不存在对应深度的节点我们才插入
                rightmost_value_at_depth.setdefault(depth, node.val)

                stack.append((node.left, depth + 1))
                stack.append((node.right, depth + 1))

        return [rightmost_value_at_depth[depth] for depth in range(max_depth + 1)]

时间复杂度:O(n)

空间复杂度:O(n)

解题思路三:0

python 复制代码

时间复杂度:O(n)

空间复杂度:O(n)

相关推荐
青 春 记 忆1 小时前
LeetCode 104. 二叉树的最大深度|Python 解法详解
python·算法·leetcode
evans在进步4 小时前
LeetCode 198:打家劫舍——Java 动态规划详解
java·leetcode·动态规划
Nil2085 小时前
leetcode 234回文链表
算法·leetcode·链表
ZC跨境爬虫5 小时前
LeetCode 119. 杨辉三角 II(原地更新优化详解 + Java Python 实现)
java·python·leetcode
吃着火锅x唱着歌5 小时前
LeetCode 3597.分割字符串
算法·leetcode·职场和发展
Nil20818 小时前
leetcode 160相交链表
算法·leetcode·链表
ZC跨境爬虫20 小时前
LeetCode 108. 将有序数组转换为二叉搜索树(递归构建详解 + Java Python 实现)
java·python·leetcode
Tisfy21 小时前
LeetCode 3090.每个字符最多出现两次的最长子字符串:二重循环 / 滑动窗口
算法·leetcode·字符串·题解·模拟·双指针·滑动窗口
LuminousCPP21 小时前
栈和队列专题(一):LeetCode 20. 有效的括号
数据结构·经验分享·笔记·leetcode·手写栈
.道阻且长.1 天前
8.LeetCode算法习题讲解--滑动窗口--长度最小的子数组
算法·leetcode·职场和发展