【二叉树】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),最坏情况下队列的大小为二叉树的最大宽度
相关推荐
TImCheng060914 分钟前
内容运营岗位适合考哪个AI证书,与算法认证侧重点分析
人工智能·算法·内容运营
赵域Phoenix24 分钟前
混沌系统是什么?
人工智能·算法·机器学习
CoderCodingNo29 分钟前
【GESP】C++五、六级练习题 luogu-P1886 【模板】单调队列 / 滑动窗口
开发语言·c++·算法
paeamecium30 分钟前
【PAT甲级真题】- All Roads Lead to Rome (30)
数据结构·c++·算法·pat考试·pat
Cando学算法36 分钟前
双指针之快慢指针
算法
汀、人工智能1 小时前
[特殊字符] 第100课:任务调度器
数据结构·算法·数据库架构·贪心··任务调度器
每日任务(希望进OD版)1 小时前
二分法刷题
算法·二分
会编程的土豆1 小时前
日常做题 vlog
数据结构·c++·算法
Omigeq2 小时前
1.4 - 曲线生成轨迹优化算法(以BSpline和ReedsShepp为例) - Python运动规划库教程(Python Motion Planning)
开发语言·人工智能·python·算法·机器人
网络工程小王2 小时前
【大模型(LLM)的业务开发】学习笔记
人工智能·算法·机器学习