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

二叉树的右视图

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

示例1:
在这里插入图片描述
输入: [1,2,3,null,5,null,4]
输出: [1,3,4]

解题思路

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

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),最坏情况下队列的大小为二叉树的最大宽度

相关推荐

  1. 199_视图

    2024-03-30 01:34:01       51 阅读
  2. Leetcode 199视图

    2024-03-30 01:34:01       31 阅读
  3. LeetCode199.视图

    2024-03-30 01:34:01       26 阅读
  4. 力扣199. 视图

    2024-03-30 01:34:01       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-30 01:34:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-30 01:34:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-30 01:34:01       87 阅读
  4. Python语言-面向对象

    2024-03-30 01:34:01       96 阅读

热门阅读

  1. 11、Spring CLI中Action指南

    2024-03-30 01:34:01       42 阅读
  2. yarn的安装和使用

    2024-03-30 01:34:01       48 阅读
  3. js中遍历数组,map方法和reduce方法有什么区别?

    2024-03-30 01:34:01       39 阅读
  4. 为什么编码器-解码器结构能够保存空间信息

    2024-03-30 01:34:01       40 阅读
  5. <个人笔记>位运算

    2024-03-30 01:34:01       39 阅读
  6. Frida相关脚本代码样例(Windows下经过测试)

    2024-03-30 01:34:01       46 阅读
  7. 前端通用命名规范和Vue项目命名规范

    2024-03-30 01:34:01       41 阅读
  8. GIT使用小结

    2024-03-30 01:34:01       40 阅读