力扣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;
    }
}
相关推荐
zander2584 分钟前
LeetCode 79. 单词搜索
算法·深度优先
老洋葱Mr_Onion14 分钟前
【C++】高精度模板
开发语言·c++·算法
脚踏实地皮皮晨41 分钟前
003003002_WPF Grid 基类官方类定义逐行深度解析
开发语言·windows·算法·c#·wpf·visual studio
aaaameliaaa9 小时前
字符函数和字符串函数
c语言·笔记·算法
城管不管10 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
月疯10 小时前
二分法算法(水平等分图形面积)
算法
豆瓣鸡10 小时前
算法日记 - Day3
java·开发语言·算法
白白白小纯11 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang11 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
The Chosen One98511 小时前
高进度算法模板速记(待完善)
java·前端·算法