【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);
    }
    
}
相关推荐
gihigo19987 小时前
matlab 基于瑞利衰落信道的误码率分析
算法
foxsen_xia8 小时前
go(基础06)——结构体取代类
开发语言·算法·golang
foxsen_xia8 小时前
go(基础08)——多态
算法·golang
leoufung8 小时前
用三色 DFS 拿下 Course Schedule(LeetCode 207)
算法·leetcode·深度优先
im_AMBER9 小时前
算法笔记 18 二分查找
数据结构·笔记·学习·算法
C雨后彩虹9 小时前
机器人活动区域
java·数据结构·算法·华为·面试
MarkHD9 小时前
车辆TBOX科普 第53次 三位一体智能车辆监控:电子围栏算法、驾驶行为分析与故障诊断逻辑深度解析
算法
苏小瀚10 小时前
[算法]---路径问题
数据结构·算法·leetcode
月明长歌10 小时前
【码道初阶】一道经典简单题:多数元素(LeetCode 169)|Boyer-Moore 投票算法详解
算法·leetcode·职场和发展
wadesir10 小时前
C语言模块化设计入门指南(从零开始构建清晰可维护的C程序)
c语言·开发语言·算法