力扣面试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;
    }
}
相关推荐
aaaameliaaa8 小时前
字符函数和字符串函数
c语言·笔记·算法
城管不管9 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
月疯9 小时前
二分法算法(水平等分图形面积)
算法
豆瓣鸡9 小时前
算法日记 - Day3
java·开发语言·算法
白白白小纯10 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang10 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
The Chosen One98510 小时前
高进度算法模板速记(待完善)
java·前端·算法
圣保罗的大教堂12 小时前
leetcode 3517. 最小回文排列 I 中等
leetcode
kyriewen12 小时前
面试官让我手写虚拟列表——AI生成的版本,快速滚动几下就白屏了
前端·javascript·面试
土豆.exe12 小时前
Fastjson2 2.0.53 哈希碰撞 RCE:从原理到三种打法
算法·哈希算法