Easy-题目27:107.Binary Tree Level Order Traversal II

题目原文:
Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).
题目大意:
给出一个二叉树,求层次遍历结果。其中,层次靠后的先输出。
题目分析:
与普通的层次遍历不同,本题要求输出为二维数组,其中第一层维度代表层数。因此使用了两个队列,分别记录节点和层数。每次层数发生变化时,将当前数组(第二层数组)加入第一层。
源码:(language:java)

public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        Queue<Integer> levelqueue=new LinkedList<Integer>();

        queue.add(root);
        levelqueue.add(1);
        List<List<Integer>> result=new ArrayList();
        List<Integer> temp=new ArrayList<Integer>();
        if(root==null)
            return result;
        while(!queue.isEmpty())     {
            TreeNode current=queue.remove();
            int curLevel=levelqueue.remove();           
            if(curLevel==result.size()) {
                temp.add(current.val);
            }
            else    {
                result.add(temp);               

                temp=new ArrayList<Integer>();
                temp.add(current.val);  
            }
            if(current.left!=null) {
                queue.add(current.left);
                levelqueue.add(curLevel+1);
            }
            if(current.right!=null) {
                queue.add(current.right);
                levelqueue.add(curLevel+1);
            }
        }
        result.add(temp);
        result.remove(0);
        Collections.reverse(result);
        return result;        
    }
}

成绩:
4ms,beats 10.19%,众数3ms,46.84%
Cmershen的碎碎念:
本题成绩较差,代码逻辑也很混乱,应该是因为处理的过程中流程过于复杂,且最后一步将数组翻转比较浪费时间。应考虑使用堆栈和队列两种数据结构存储数组。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值