【二叉树】Leetcode 199. 二叉树的右视图【中等】

二叉树的右视图

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

示例1:

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

输出: [1,3,4]

解题思路

可以使用 广度优先搜索(BFS)进行二叉树的层次遍历,每一层最后一个节点即为从右侧看到的节点。

Java实现

java 复制代码
public class RightSideView {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int val) {
            this.val = val;
        }
    }

    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();

                // Add the last node's value in each level to the result list
                if (i == size - 1) {
                    result.add(node.val);
                }

                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }

        return result;
    }

    public static void main(String[] args) {
        // Create a simple binary tree for testing
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(4);

        RightSideView solution = new RightSideView();
        List<Integer> result = solution.rightSideView(root);

        // Output: [1, 3, 4]
        System.out.println(result);
    }
}

时间空间复杂度

  • 时间复杂度:O(n),其中n是二叉树中的节点数,每个节点都需要访问一次。
  • 空间复杂度:O(width),最坏情况下队列的大小为二叉树的最大宽度
相关推荐
add45a26 分钟前
C++中的观察者模式
开发语言·c++·算法
进击的小头29 分钟前
第13篇:基于伯德图的超前_滞后校正器深度设计
python·算法
leaves falling30 分钟前
二分查找:迭代与递归实现全解析
数据结构·算法·leetcode
做怪小疯子36 分钟前
Leetcode刷题——深度优先搜索(DFS)
算法·leetcode·深度优先
大数据AI人工智能培训专家培训讲师叶梓1 小时前
120B 数学语料 + GRPO 算法,DeepSeekMath 刷新开源大模型推理天花板
人工智能·算法·大模型·推理·deepseek·openclaw·openclaw 讲师
IMPYLH1 小时前
Linux 的 comm 命令
linux·运维·算法
薛定谔的悦1 小时前
嵌入式设备OTA升级实战:从MQTT命令到自动重启的全流程解析
linux·算法·ota·ems
杰克尼1 小时前
知识点总结--01
数据结构·算法
cici158741 小时前
图像匹配算法:灰度相关法、相位相关法与金字塔+相位相关法
算法
佚名ano1 小时前
支持向量机SVM的简单推导过程
算法·机器学习·支持向量机