【二叉树】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),最坏情况下队列的大小为二叉树的最大宽度
相关推荐
Rubisco..2 小时前
牛客周赛 Round 111
数据结构·c++·算法
兮山与2 小时前
算法8.0
算法
高山上有一只小老虎2 小时前
杨辉三角的变形
java·算法
Swift社区2 小时前
LeetCode 395 - 至少有 K 个重复字符的最长子串
算法·leetcode·职场和发展
Espresso Macchiato2 小时前
Leetcode 3710. Maximum Partition Factor
leetcode·职场和发展·广度优先遍历·二分法·leetcode hard·leetcode 3710·leetcode双周赛167
hz_zhangrl2 小时前
CCF-GESP 等级考试 2025年9月认证C++四级真题解析
开发语言·c++·算法·程序设计·gesp·c++四级·gesp2025年9月
少许极端2 小时前
算法奇妙屋(六)-哈希表
java·数据结构·算法·哈希算法·散列表·排序
羊羊小栈2 小时前
基于「多模态大模型 + BGE向量检索增强RAG」的新能源汽车故障诊断智能问答系统(vue+flask+AI算法)
vue.js·人工智能·算法·flask·汽车·毕业设计·大作业
Da Da 泓2 小时前
shellSort
java·数据结构·学习·算法·排序算法
2013编程爱好者3 小时前
计算时间复杂度
c++·算法·排序算法