[Lintcode] Binary Tree Level Order Traversal I & II
2015-10-07 12:06
369 查看
Binary Tree Level Order Traversal I
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).Example
Given binary tree
{3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
SOLUTION :
这个题有很多解法,包括用两个queue,一个queue+dummy node 以及只用一个queue的,这里就只说最优解,1 queue的了。
本题借鉴了大神的总结:http://www.1point3acres.com/bbs/thread-139294-1-1.html
基本上几个level order 的二叉树遍历都可以用这套思路。
思路:用queue去模拟层序遍历的过程,就是说要向queue中一层一层的输入,再输出,但是怎么保证输入的是同一层呢,我们用到一个变量,queue.size(),这个很关键,它保证了内层循环(负责向queue输入节点以及从queue拿出节点加入list中)执行次数就是这一层节点的个数。在实现时候的具体思想就是,拿出一个点,就把这个点的左右儿子加入到queue中,从任一一层二叉树来看,就是当这一层的所有点抖拿出来了之后,同时这些点的所有左右儿子也都加进去了。具体实现看代码:
注意事项,queue用LinkedList模拟,queue输入输出分别是add(),remove()。
public class Solution { /** * @param root: The root of binary tree. * @return: Level order a list of lists of integer */ public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (root == null){ return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while (!queue.isEmpty()){ ArrayList<Integer> list = new ArrayList<Integer>();// 一定要把list建在while loop里面,放在外面的话,每次list不会重新renew,会有重复的在里面,还要专门删一次 int size = queue.size(); for (int i = 0; i < size; i++){ TreeNode cur = queue.remove(); if (cur.left != null){ queue.add(cur.left); } if (cur.right != null){ queue.add(cur.right); } list.add(cur.val); } result.add(new ArrayList<Integer>(list)); } return result; } }
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).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] ]
SOLUTION :
这个题其实跟I是完全一样的,考点没太看懂,只要最后把list加入result的时候从前向后加就好啦,或者reverse一下啊,没什么难度,代码略了。
相关文章推荐
- Foundation框架之文件操作
- hihoCoder 1228 Mission Impossible 6(模拟)
- 5.Python补充_字符串格式化 (%操作符)
- ContextLoaderListener使用
- jQuery.when(deferreds)
- 用于科创的git log美化输出
- shiro安全框架扩展教程--如何扩展实现集中式session管理(redis,memcached等)
- go语言 类型:整型
- hihoCoder 1227 The Cats' Feeding Spots(水)
- Android 最火的快速开发框架XUtils
- jqXHR对象
- Notes on reading: Functional Programming in Scala - Part 1
- *Valid Anagram
- Cocos2D粒子发射器的纹理
- Cocos2D粒子发射器的纹理
- Cocos2D粒子发射器的纹理
- Makefile中的$(@:_config=)什么意思?
- 【学习OpenCV】第一章 安装OpenCV
- 0917词法分析
- UESTC 1711 Divide 位操作模拟题