力扣面试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;
    }
}
相关推荐
可靠的仙人掌6 分钟前
SAC(Soft Actor-Critic)算法底座
开发语言·算法·php
海石1 小时前
单调栈复健,顺便,牺牲一下吧,空间复杂度!一切献给AC
算法·leetcode
海石1 小时前
JS击败94%,Hard题想不到动态规划,那就用数组和栈试试
算法·leetcode
alphaTao4 小时前
LeetCode 每日一题 2026/7/6-2026/7/12
算法·leetcode
想吃火锅10054 小时前
【leetcode】56.合并区间js
算法·leetcode·职场和发展
imuliuliang4 小时前
可合并堆在多任务调度中的优势与实现技巧7
算法
学究天人4 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷6)
网络·算法·数学建模·动态规划·几何学·图论·拓扑学
wabs6664 小时前
关于动态规划【力扣72.编辑距离的思考】
算法·leetcode·动态规划
用户852495071844 小时前
从零搭建自定义 MCP Server:打造你的专属工具服务
面试
黄敬峰4 小时前
远程 MCP 实战:LangChain 同时接入高德地图、Chrome、文件系统,让 AI Agent 操控真实世界
面试