【力扣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);
            }
            
        }
    }
}
相关推荐
Beginner x_u40 分钟前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
_深海凉_4 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
踩坑记录5 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
旖-旎5 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰5 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习
Mr_pyx5 小时前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先
AIFarmer5 小时前
【无标题】
开发语言·c++·算法
AGV算法笔记5 小时前
CVPR 2025 最新感知算法解读:GaussianLSS 如何用 Gaussian Splatting 重构 BEV 表示?
算法·重构·自动驾驶·3d视觉·感知算法·多视角视觉
勤劳的进取家6 小时前
数据链路层基础
网络·学习·算法
Advancer-7 小时前
第二次蓝桥杯总结(上)
java·算法·职场和发展·蓝桥杯