【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);
    }
    
}
相关推荐
篮l球场11 分钟前
合并 K 个升序链表
算法
苦藤新鸡11 分钟前
87.分割成两个等和数组 leetcode416
数据结构·算法·leetcode
炽烈小老头13 分钟前
【 每天学习一点算法 2026/03/11】从前序与中序遍历序列构造二叉树
学习·算法
进击切图仔14 分钟前
ROS 行为(Action)机制
算法
飞Link16 分钟前
概率图模型的基石:隐马可夫模型 (HMM) 深度解析
开发语言·python·算法
_日拱一卒16 分钟前
LeetCode(力扣):验证回文串
算法·leetcode·职场和发展
Eward-an18 分钟前
LeetCode 128. 最长连续序列(O(n)时间复杂度详解)
数据结构·算法·leetcode
Frostnova丶19 分钟前
LeetCode 1009 & 476 数字的补数
算法·leetcode
CppBlock20 分钟前
HPX vs TBB vs OpenMP:并行任务模型对比
c++·算法