【LeetCode热题100】--199.二叉树的右视图

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

    public void dfs(TreeNode root,int high){
        if(root == null){
            return ;
        }
        if(maxHigh < high){
            res.add(root.val);
            maxHigh = high;
        }
        dfs(root.right,high + 1);
        dfs(root.left,high + 1);
    }
    
}
相关推荐
INGNIGHT10 分钟前
984.不含 AAA 或 BBB 的字符串(贪心)
开发语言·算法·leetcode
飞天狗11113 分钟前
2025第十六届蓝桥杯c/c++B组国赛题解
c语言·c++·算法·蓝桥杯
超梦dasgg19 分钟前
Tarjan算法解 强连通分量 & 循环依赖
算法·深度优先·图论
散峰而望41 分钟前
【算法练习】算法练习精选:从 Phone numbers 到 Decrease,覆盖字符串、模拟、图论思维题
数据结构·c++·算法·贪心算法·github·动态规划·图论
人道领域1 小时前
【LeetCode刷题日记】538.把二叉搜索树转换为累加树
java·开发语言·后端·算法·leetcode
Lsk_Smion1 小时前
力扣实训 _ [33].搜索旋转排序数组 _ [92].翻转链表Ⅱ
java·数据结构·算法
MrZhao4001 小时前
多 Agent 协作与通信:MessageBus 最小实现
算法
Zhang~Ling1 小时前
二叉搜索树(BST)详解:插入、删除、查找与 Key/Value 实战场景
数据结构·c++·算法
8Qi81 小时前
LeetCode 76. 最小覆盖子串(Minimum Window Substring)
数据结构·算法·leetcode·滑动窗口·哈希表
weixin_BYSJ19871 小时前
springboot旅游管理系统04470(附源码+开发文档+部署教程)
java·spring boot·python·算法·django·flask·旅游