【力扣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);
            }
            
        }
    }
}
相关推荐
运行时记录22 分钟前
别再手动写提示词了 — SkillOpt 让技能文档自己进化
算法
啦啦啦啦啦zzzz35 分钟前
算法总结(二分查找、双指针)
c++·算法
qq_8573058191 小时前
python语法
开发语言·python·算法
DXM05211 小时前
第9期|从机器学习到深度学习:AI遥感解译的进化逻辑
人工智能·算法·计算机视觉
小蒋学算法1 小时前
算法-阶乘函数后K个零
算法
weixin_307779132 小时前
智能模拟数据生成平台:生成式AI合成数据技术重塑开发测试效能
人工智能·测试工具·算法·测试用例
羊羊小栈3 小时前
Uplift营销供应链协同决策系统(基于Uplift因果推断与运筹优化算法)
前端·人工智能·算法·毕业设计·大作业
金融小师妹3 小时前
AI因子共振模型显示:金银比突破区间上沿,白银定价逻辑进入再校准阶段
人工智能·算法·均值算法·线性回归
J2虾虾3 小时前
C语言 typedef 用法
c语言·数据结构·算法
hunterkkk(c++)3 小时前
线段树例题
算法