【二叉树】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),最坏情况下队列的大小为二叉树的最大宽度
相关推荐
一条大祥脚16 分钟前
ABC460贪心|多源BFS|数论|计数|线段树|树的直径
算法·宽度优先
小欣加油26 分钟前
leetcode121买卖股票的最佳时机
数据结构·c++·算法·leetcode·职场和发展
暖阳华笺1 小时前
【高频考点】K-Means聚类算法
c++·算法·机器学习·kmeans·聚类
下午写HelloWorld1 小时前
后量子密码算法:协同签名研究综述
算法·密码学·后量子·协同签名
小蒋学算法1 小时前
算法-计算右侧小于当前元素的个数-分治&归并思想
java·数据结构·算法
lqqjuly1 小时前
FlashAttention 深度解析
人工智能·深度学习·算法
满怀冰雪1 小时前
第05篇-滑动窗口算法-一套模板解决子串与子数组问题
java·算法
叫我:松哥1 小时前
基于LSTM与ARIMA的城市空气质量分析与预测系统
人工智能·python·rnn·算法·机器学习·flask·lstm
j7~1 小时前
【C++】模板初阶--函数模板,类模板详解
数据结构·c++·算法·函数模板·类模板·函数模板实例化
无限码力2 小时前
阿里算法岗 0530笔试真题 - 寻找满足条件的最优子序列
算法·阿里笔试真题·阿里机试真题·阿里算法岗笔试真题·阿里算法题