每天一道leetcode-107-二叉树的层次遍历 II

辣条走起,每月的leetcode刷题99元奖励就靠大家啦~

前言

今天有点事题目先刷了107了,105,106接下来发

今天的题目
每天的题目见github(看最新的日期):
https://github.com/gzc426

昨天的题解

每天一道leetcode-107-二叉树的层次遍历 II

题目

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],

每天一道leetcode-107-二叉树的层次遍历 II_第1张图片

题目详解

代码

 
/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/

class Solution {
   public List<List> levelOrderBottom(TreeNode root) {
       List<List> list = new ArrayList<>();
       List tempList = new ArrayList<>();
       if(root == null)
           return list;
       Queue queue = new LinkedList<>();
       queue.add(root);
       int toBePrint = 1;//这一层要打印的节点
       int nextLevelCount = 0;//下一层需要打印节点
       while(queue.isEmpty() == false)//队列不为空
       {
           TreeNode temp = queue.poll();//出队
           tempList.add(temp.val);//把需要的val保存下来
           toBePrint--;//每出队一个,这层要打印的节点数就减少一个
           if(temp.left != null)
           {
               queue.add(temp.left);//入队,先入先出,所以左子树先打印
               nextLevelCount++;//统计下一层节点
           }
           if(temp.right != null)
           {
               queue.add(temp.right);//和上面类似
               nextLevelCount++;
           }
           if(toBePrint == 0)//当这一层节点打印完了
           {
               list.add(new ArrayList<>(tempList));//把这一行的结果保存
               tempList.clear();
               toBePrint = nextLevelCount;//下一层打印的节点,进行赋值
               nextLevelCount = 0;//下下层节点初始值置位0,准备开始计数
           }
       }
       List<List> result = new ArrayList<>();//新建一个数组
       for(int i=list.size()-1;i>=0;i--)
           result.add(list.get(i));//逆序添加
       return result;  
   }
}

代码截图(避免乱码)

每天一道leetcode-107-二叉树的层次遍历 II_第2张图片

结束语

作者乔戈里亲历2019秋招,哈工大计算机本硕,百度java工程师,欢迎大家关注我的微信公众号:程序员乔戈里,公众号有3T编程资源,以及我和我朋友(百度C++工程师)在秋招期间整理的近200M的面试必考的java与C++面经,并有每天一道leetcode打卡群与技术交流群,欢迎关注。

你可能感兴趣的:(每天一道leetcode-107-二叉树的层次遍历 II)