【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);
    }
    
}
相关推荐
神威难绷泪15 分钟前
Linux应用软件编程:线程分离属性 互斥机制 同步机制 死锁
linux·开发语言·算法·线程
小星星闪亮登场33 分钟前
图论--最小生成树(内含二分图)
数据结构·算法·图论·迭代加深·图搜索算法
ZC跨境爬虫1 小时前
LeetCode 219. 存在重复元素 II(滑动窗口 + 哈希表详解)
算法·leetcode·散列表
吞下星星的少年·-·1 小时前
The 2025 ICPC Asia East Continent Online Contest (I) A题(模拟+贪心)
算法·贪心·模拟
小程序设计1 小时前
【机械设计】磁粉检测机器人的设计与验证
算法·机器人
Navigator_Z1 小时前
LeetCode //C - 1220. Count Vowels Permutation
c语言·算法·leetcode
吃好睡好便好2 小时前
判断函数的使用
学习·算法·matlab·生活·判断函数
2601_956121972 小时前
线性DP(入门)
c++·算法·动态规划
feilieren2 小时前
leetcode - 389. 找不同
算法·leetcode
挽星安2 小时前
2026/8/29
数据结构·算法