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算平均分

相关推荐
怕浪猫5 小时前
RAG 面试 6 连问,从原理到优化全部覆盖
python·算法·面试
无线通信科研笔记5 小时前
IEEE TVT 2026 论文精读与完整复现|相位误差如何重塑近场 RIS 的幅相响应
论文阅读·人工智能·python·算法·论文笔记
mmmmath_36 小时前
二叉树の递归遍历
算法
All for pursuit.7 小时前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
小师兄吃牛肉7 小时前
C语言中的nullptr有必要吗
c语言·c++·算法
一只小小的芙厨9 小时前
【线性DP】
学习·算法·动态规划
奋发向前wcx9 小时前
CSP-J复赛模拟赛5 王晨旭补题 2026.10.5
算法
罗湖老棍子11 小时前
C Looooops(信息学奥赛一本通- P1640)
算法·数论·同余·裴蜀定理·扩展欧几里得
Interview Aid11212 小时前
OpenAI SWE 面试流程
面试·职场和发展
我命由我1234512 小时前
Photoshop - Photoshop 使用对齐功能定位元素
学习·职场和发展·产品运营·求职招聘·职场发展·产品经理·学习方法