每日一练 | Day 3

199. 二叉树的右视图

题目链接

https://leetcode.cn/problems/binary-tree-right-side-view

相关算法

二叉树、广度优先搜索

题目描述

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

  • 数据范围:
    二叉树的节点个数的范围是 [0,100]
    -100 <= Node.val <= 100

解题思路

因为我们预先无法知道二叉树的具体形状,因此无法直接求得二叉树最右侧的所有节点,但是如果使用层序遍历,我们可以很轻松得到,每层最右边的节点或者说是最后一个节点就是我们想要求的内容

完整代码

java 复制代码
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        queue.add(null);
        while (!queue.isEmpty() && queue.peek() != null) {
            TreeNode node = queue.poll();
            while (node != null) {
                if (queue.peek() == null) {
                    res.add(node.val);
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                node = queue.poll();
            }
            queue.add(null);
        }
        return res;
    }
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

相对来说今天的题目不难,就只是二叉树层序遍历最基本的运用方式。

相关推荐
非优秀程序员1 天前
第05章 播放器大战,暴风、快播与那一夜|《互联网产品恩仇录》
算法
武子康1 天前
驾驶轨迹换个坐标,就能给移动机器人用吗?
人工智能·算法·机器学习
lisw052 天前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
一起学安全技术2 天前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs2 天前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信150413057592 天前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
GoAI2 天前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi2 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵