力扣hot100 - 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();
        Queue<TreeNode> q = new LinkedList();
        if(root == null) return res;
        q.add(root);

        while(!q.isEmpty()){
            int l = q.size();
            while(l > 0){
            TreeNode cur = q.peek();
            q.poll();
            if(l == 1){
                res.add(cur.val);
            }
            l--;
            if(cur.left != null){
                q.add(cur.left);
            }
            if(cur.right != null){
                q.add(cur.right);
            }
            }
        }
        return res;
    }
}
相关推荐
渡过晚枫9 小时前
[第十四届蓝桥杯/java/算法]国赛A——跑步计划
算法
hanlin039 小时前
刷题笔记:力扣第17题-电话号码的字母组合
笔记·算法·leetcode
不是株9 小时前
算 法
数据结构·python·算法
云泽8089 小时前
蓝桥杯算法精讲:从宏观角度重新认识递归
算法·职场和发展·蓝桥杯
自信150413057599 小时前
插入排序算法
c语言·数据结构·算法·排序算法
阿Y加油吧9 小时前
力扣打卡day09——缺失的第一个正数、矩阵置零
数据结构·算法·leetcode
2301_818419019 小时前
C++中的状态模式实战
开发语言·c++·算法
仰泳的熊猫9 小时前
题目2576:蓝桥杯2020年第十一届省赛真题-解码
数据结构·c++·算法·蓝桥杯
CSDN_kada9 小时前
杭电网安复试编程Day23
c++·考研·算法
灰色小旋风9 小时前
力扣16 最接近的三数之和(C++)
数据结构·c++·算法·leetcode