【力扣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);
            }
            
        }
    }
}
相关推荐
珂朵莉MM几秒前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第3赛季优化题--多策略混合算法
人工智能·算法
罗西的思考7 分钟前
【OpenClaw】通过 Nanobot 源码学习架构---(6)Skills
人工智能·深度学习·算法
枫叶林FYL11 分钟前
【自然语言处理 NLP】7.2 红队测试与对抗鲁棒性(Red Teaming & Adversarial Robustness)
人工智能·算法·机器学习
qiqsevenqiqiqiqi13 分钟前
字符串模板
算法
Fcy64823 分钟前
算法基础详解(六)倍增思想与离散化思想
算法·快速幂·离散化·倍增算法
wuweijianlove37 分钟前
算法调度问题中的代价模型与优化方法的技术5
算法
Dxy123931021642 分钟前
Python路径算法简介
开发语言·python·算法
And_Ii1 小时前
LCR 132.砍竹子Ⅱ
算法
汀、人工智能1 小时前
[特殊字符] 第67课:跳跃游戏II
数据结构·算法·数据库架构·图论·bfs·跳跃游戏ii