前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LintCode 二叉树的层次遍历 II题目代码

LintCode 二叉树的层次遍历 II题目代码

作者头像
desperate633
发布2018-08-22 12:17:41
2870
发布2018-08-22 12:17:41
举报
文章被收录于专栏:desperate633

题目

给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)

样例 给出一棵二叉树 {3,9,20,#,#,15,7},

Paste_Image.png

代码

代码语言:javascript
复制
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
 
 
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: buttom-up level order a list of lists of integer
     */
    public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
        // write your code here
        if(root == null)
            return new ArrayList<>();
        
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        
        Queue<TreeNode> list = new LinkedList<>();
        
        list.offer(root);
        
        while(!list.isEmpty()) {
            int size = list.size();
            ArrayList<Integer> level = new ArrayList<>();
            for(int i=0;i<size;i++) {
                TreeNode cur = list.poll();
                level.add(cur.val);
                if(cur.left != null)
                    list.offer(cur.left);
                if(cur.right != null)
                    list.offer(cur.right);
            }
            res.add(level);
        }
        Collections.reverse(res);
        return res;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017.03.15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档