【二叉树】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),最坏情况下队列的大小为二叉树的最大宽度
相关推荐
元亓亓亓14 分钟前
LeetCode热题100--206.反转链表--简单
算法·leetcode·链表
边跑边掩护20 分钟前
LeetCode 373 查找和最小的 K 对数字题解
leetcode
诚丞成29 分钟前
BFS算法篇——从晨曦到星辰,BFS算法在多源最短路径问题中的诗意航行(上)
java·算法·宽度优先
hongjianMa30 分钟前
2024睿抗编程赛国赛-题解
算法·深度优先·图论·caip
czy87874751 小时前
两种常见的C语言实现64位无符号整数乘以64位无符号整数的实现方法
c语言·算法
yzx9910131 小时前
支持向量机案例
算法·机器学习·支持向量机
天上路人1 小时前
采用AI神经网络降噪算法的语言降噪消回音处理芯片NR2049-P
深度学习·神经网络·算法·硬件架构·音视频·实时音视频·可用性测试
chao_7891 小时前
手撕算法(定制整理版2)
笔记·算法
AndrewHZ3 小时前
【图像处理基石】什么是油画感?
图像处理·人工智能·算法·图像压缩·视频处理·超分辨率·去噪算法
.格子衫.3 小时前
015枚举之滑动窗口——算法备赛
数据结构·算法