LeetCode:199二叉树的右视图

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();

        if(root == null){
            return res;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while(!queue.isEmpty()){
            int size = queue.size();

            for(int i = 0; i < size; i++){
                TreeNode current = queue.poll();
                //这个判断条件代表刚好落在了该层最右边的元素上
                if(i == size - 1){
                    res.add(current.val);
                }
                //左右节点入队
                if(current.left != null){
                    queue.offer(current.left);
                }
                if(current.right != null){
                    queue.offer(current.right);
                }
            }
        }
        return res;
    }
}

思路:

计算每一层的节点数,然后循环将该层节点的最后一个存放进res即可。

如果求左视图:直接将判断条件改成if(i == 0)即可

如果求二叉树的层平均值:在for循环中加入sum += current.val,循环结束后用sum/size算平均分

相关推荐
forest_096 小时前
《AI 编程 Harness 实战手册》04|审批这道门:点了一百次“允许”,还剩多少作用?
人工智能·算法·prompt·agi
H.莓飛6 小时前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
不会武功不懂江湖8 小时前
RISC-V链接器与链接脚本
汇编·算法·risc-v
Zwawa9 小时前
卡尔曼到底在算什么:从一维到它的变式以及工程版卡尔曼滤波算法C语言实现
c语言·算法·嵌入式
电科_银尘9 小时前
【大模型算法与工程 14】Tokenizer与Embedding:文本如何变成模型输入
算法·embedding
饮水桶_T11 小时前
Python 面向对象(十七)|继承、封装、多态 笔记
数据结构·笔记·算法
文丑颜不良啊12 小时前
LeetCode3281~3300题目解析
java·leetcode
地平线开发者14 小时前
让 AI Agent 和 征程6 台架高效、稳定、安全地协作
算法·安全·自动驾驶
kyle~14 小时前
SHA-256 哈希去重
算法·哈希算法