【二叉树】199. 二叉树的右视图

☞梦想进大厂的一只程序猿☜

☞期望毕业前力扣刷够400题☜

☞正在复习数据结构和算法☜

☞博客地址:https://www.huangliangshuai.com/

1. 题目描述

在这里插入图片描述

2. 题目分析

  1. 在很多的面经中看到过这种题,今天有空做了做
  2. 让你求二叉树的左视图或者右视图,我们可以直接层次遍历,对于层次遍历,参考这道题–102. 二叉树的层次遍历, 我们只需要取出每次层次遍历的第一个数或者最后一个数,存进list中,最后输出
  3. 这个题目的关键思想是在:int len = quene.size(); for(int i = 0; i < len; i++){}

3. 题目代码

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
		List<Integer> list = new ArrayList<Integer>();
        if(root == null){
            return list;
        }
        queue.add(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = size; i > 0; i--){
                TreeNode tree = queue.poll();
                if(tree.left != null){
                queue.add(tree.left);
                }
                if(tree.right != null){
                queue.add(tree.right);
                }
                if(i == 1){
                list.add(tree.val);
                }
            }
        }
        return list;        
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40915439/article/details/107849322