【力扣Hot100】刷题日记

D32

二叉树的右视图

二叉树的右视图

DFS

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 {
    List<Integer> list = new ArrayList<>();
    public List<Integer> rightSideView(TreeNode root) {
        
        dfs(root, 1);
        return list;
    }

    public void dfs(TreeNode root, int height){
        if(root == null) return;
        if(height > list.size()) list.add(root.val);
        dfs(root.right, height + 1);
        dfs(root.left, height + 1);
    }
}

BFS

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 {
    List<Integer> list = new ArrayList<>();
    Queue<TreeNode> queue = new ArrayDeque<>();
    public List<Integer> rightSideView(TreeNode root) {
        if(root != null) queue.add(root);
        bfs(root);
        return list;
    }

    public void bfs(TreeNode root){
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0; i < size; i++){
                // 层序遍历,但只留最右一个节点
                TreeNode node = queue.poll();
                if(node.left != null) queue.add(node.left);
                if(node.right != null) queue.add(node.right);
                if(i == size - 1) list.add(node.val);
            }
            
        }
    }
}
相关推荐
生莫甲鲁浪戴3 小时前
Android Studio新手开发第三十一天
android studio·1024程序员节
Dev7z3 小时前
基于Swin Transformer的宠物皮肤病诊断系统
1024程序员节
DuHz3 小时前
使用稀疏采样方法减轻汽车雷达干扰——论文阅读
论文阅读·算法·汽车·信息与通信·信号处理
王老师青少年编程3 小时前
AtCoder真题及详细题解 ABC427C: Bipartize
c++·题解·1024程序员节·atcoder·csp·abc·信奥赛
gAlAxy...3 小时前
面试JAVASE基础(五)——Java 集合体系
java·python·面试·1024程序员节
B站计算机毕业设计之家4 小时前
计算机视觉python口罩实时检测识别系统 YOLOv8模型 PyTorch 和PySide6界面 opencv (建议收藏)✅
python·深度学习·opencv·计算机视觉·cnn·1024程序员节
大肘子咒你4 小时前
数字狂潮来袭
数据结构·c++·1024程序员节
hansang_IR4 小时前
【算法速成课 3】康托展开(Cantor Expansion)/ 题解 P3014 [USACO11FEB] Cow Line S
c++·算法·状态压缩·康托展开·排列映射
m0_748233644 小时前
【类与对象(中)】C++类默认成员函数全解析
开发语言·c++·算法