力扣面试150题--二叉树的右视图

Day 53

题目描述

思路

采取层序遍历,利用一个high的队列来保存每个节点的高度,highb和y记录上一个节点的高度和节点,在队列中,如果队列中顶部元素的高度大于上一个节点的高度,说明上一个节点就是上一层中最右边的元素,加入数组即可,同时最后需要处理最后一个元素,因为最后一个元素没有能比较的了,需要手动加入数组。

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 {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer>list=new ArrayList<Integer>();
        if(root==null){
            return list;
        }
        Queue<TreeNode> stack=new LinkedList<>();
        Queue<Integer> high=new LinkedList<>();
        stack.offer(root);
        high.offer(0);
        TreeNode x=root;
        TreeNode y=root;
        int highb=0;
        while(!stack.isEmpty()){
            if(high.peek()>highb){
                list.add(y.val);
            }
            y=stack.peek();
            highb=high.peek();
            x=stack.poll();
            high.poll();
            if(x.left!=null){
                stack.offer(x.left);
                high.offer(highb+1);
            }
            if(x.right!=null){
                stack.offer(x.right);
                high.offer(highb+1);
            }
        }
        list.add(x.val);
        return list;
    }
}
相关推荐
铉铉这波能秀14 分钟前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
蜡笔小马23 分钟前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
我是咸鱼不闲呀28 分钟前
力扣Hot100系列20(Java)——[动态规划]总结(下)( 单词拆分,最大递增子序列,乘积最大子数组 ,分割等和子集,最长有效括号)
java·leetcode·动态规划
唐梓航-求职中32 分钟前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
仟濹34 分钟前
【算法打卡day3 | 2026-02-08 周日 | 算法: BFS】3_卡码网99_计数孤岛_BFS | 4_卡码网100_最大岛屿的面积DFS
算法·深度优先·宽度优先
Ll130452529837 分钟前
Leetcode二叉树part4
算法·leetcode·职场和发展
颜酱1 小时前
二叉树遍历思维实战
javascript·后端·算法
宝贝儿好1 小时前
第二章: 图像处理基本操作
算法
小陈phd1 小时前
多模态大模型学习笔记(二)——机器学习十大经典算法:一张表看懂分类 / 回归 / 聚类 / 降维
学习·算法·机器学习
@––––––1 小时前
力扣hot100—系列4-贪心算法
算法·leetcode·贪心算法