Easy-题目27:107.Binary Tree Level Order Traversal II
来源:互联网 发布:mysql slow.log 删除 编辑:程序博客网 时间:2024/05/22 14:31
题目原文:
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
- Easy-题目27:107.Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II [easy] (Python)
- Leetcode 107. Binary Tree Level Order Traversal II (Easy) (cpp)
- 107.Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- 107. Binary Tree Level Order Traversal II
- Spring与MongoDB
- Lexicographical order, dictionary order, permutation
- hdu 1595 find the longest of the shortest(dijkstra)
- Flume+Hadoop+Hive的离线分析系统基本架构
- 深入浅出Mybatis-分页
- Easy-题目27:107.Binary Tree Level Order Traversal II
- Easy-题目28:27.Remove Element
- 69道Spring面试题和答案
- 用SharedPreferences存储数据
- WebService服务中,将写原始报文日志的功能由单独线程处理
- C++独孤九剑第一式——拨云见日(对象内存模型)
- 有关filter
- 视图调用控制器的方法
- Easy-题目29:26. Remove Duplicates from Sorted Array