力扣面试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;
    }
}
相关推荐
苏荷水5 小时前
day13 leetcode-hot100-24(链表3)
算法·leetcode·链表
zdy12635746888 小时前
python37天打卡
人工智能·深度学习·算法
云泽8088 小时前
模块化设计,static和extern(面试题常见)
c语言·面试·职场和发展
泽020210 小时前
C++之string的模拟实现
开发语言·数据结构·c++·算法
姬公子52110 小时前
leetcode hot100刷题日记——29.合并两个有序链表
c++·leetcode·链表
我不是小upper11 小时前
详细到用手撕transformer下半部分
算法·机器学习·transformer
coding者在努力11 小时前
高级数据结构与算法期末考试速成记录
数据结构·算法·动态规划·分治·速成·期末考试
江城开朗的豌豆11 小时前
JavaScript篇:前端兼容性历险记:那些年我们踩过的浏览器坑
前端·javascript·面试
江城开朗的豌豆11 小时前
JavaScript篇:JS事件冒泡:别让点击事件‘传染’!
前端·javascript·面试
new出对象11 小时前
C++ 中的函数包装:std::bind()、std::function<>、函数指针与 Lambda
开发语言·c++·算法