[LeetCode]Binary Tree Level Order Traversal II
2015-09-21 11:17
471 查看
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).
For example:
Given binary tree
return its bottom-up level order traversal as:
题解:采用的是bfs+queue,queue使用list来模拟的,jdk1.8 LinkedList没有实现Queue,最后用Collections.reverse(list)反转,用parentSize和childSize来统计一行的节点数。
code:
For example:
Given binary tree
{3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
题解:采用的是bfs+queue,queue使用list来模拟的,jdk1.8 LinkedList没有实现Queue,最后用Collections.reverse(list)反转,用parentSize和childSize来统计一行的节点数。
code:
public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> level = new ArrayList<List<Integer>>(); List<Integer> con = new ArrayList<Integer>(); TreeNode temp; int parentSize=1; int childSize=0; List<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); do{ temp = q.get(0); con.add(temp.val); q.remove(0); if(temp.left!=null){ q.add(temp.left); childSize++; } if(temp.right!=null){ q.add(temp.right); childSize++; } parentSize--; if(parentSize ==0){ level.add(con); parentSize = childSize; childSize=0; con = new ArrayList<Integer>(); } }while(!q.isEmpty()); Collections.reverse(level); return level; }
相关文章推荐
- 面试谈薪前,这五大问题你得知道!
- 初识EL、JSTL
- Node.js9 Events模块
- jquery live方法替代
- wss2012重装系统后恢复raid信息及导入原有虚拟磁盘
- page_load为什么会被执行2次
- 关于异常Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
- 利用Dockerfile构建一个基于centos 7,包括java 8, tomcat 7,php ,mysql+mycat的镜像
- 不停课不知今目标之贵
- HTML5 移动开发入门知识点
- HTML5 移动开发入门知识点
- HTML5 移动开发入门知识点
- hdu 5459 Jesus Is Here 2015沈阳网络赛 递推
- thread EXC_BAD_ACCESS
- List集合进行界面分页
- 机器学习---局部加权回归
- hadoop集群部署,内存,存储配置
- oracle中schema指的是什么?
- Spring mvc 绑定Date日期
- iOS 9部分问题