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)

相关推荐
圣保罗的大教堂4 小时前
leetcode 2540. 最小公共值 简单
leetcode
洛水水8 小时前
【力扣100题】53.最长回文子串
算法·leetcode·职场和发展
过期动态10 小时前
【LeetCode 热题 100】盛最多水的容器
java·数据结构·spring boot·算法·leetcode·spring cloud·职场和发展
凌波粒10 小时前
LeetCode--700.二叉搜索树中的搜索(二叉树)
算法·leetcode·职场和发展
洛水水10 小时前
【力扣100题】58.轮转数组
算法·leetcode
风筝在晴天搁浅10 小时前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表
玖釉-10 小时前
二叉树展开为链表:从先序遍历到原地指针重排
c++·windows·算法·leetcode·链表
洛水水11 小时前
【力扣100题】52.最小路径和
算法·leetcode
圣保罗的大教堂11 小时前
leetcode 3043. 最长公共前缀的长度 中等
leetcode
码之气三段.11 小时前
牛客周赛 Round 145-E(写了200行的史山)
算法·深度优先