1、题目
题目链接:https://leetcode.com/problems/binary-tree-level-order-traversal/
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:Given binary tree
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
题目的大意是从上到下,从左到右,依次输出一个二叉树的所有元素。
2、思路
首先想到的是递归,没有想出解决办法。其实用不到递归,只需要按层来循环遍历即可,遍历当前层的过程中,需要做两件事:
1、顺序收集下一层的所有节点
2、顺序收集本层节点的值
所以需要两个collector,一个全局collector用来收集的没各节点的值,一个局部collector来收集下一层的所有节点,当局部collector的size为0时,停止循环。
由此主循环的伪代码如下:
while(localCollector.eize>0){
localCollector = collect(globalCollector,localCollector)
}
return globalCollector
收集器的伪代码如下:
collect(globalCollector,localCollector){
collect this layer's value...
collect next layer's node...
}
3、实现过程
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
//local collector
List<TreeNode> tmp = new ArrayList<>();
//global collector
List<List<Integer>> collector = new ArrayList<>();
if(root != null){
tmp.add(root);
}
//main loop
while(tmp.size()>0){
tmp = collect(collector,tmp);
}
return collector;
}
private List<TreeNode> collect(List<List<Integer>> collector,List<TreeNode> tmp){
if(tmp == null || tmp.size() == 0){
return tmp;
}
List<TreeNode> _tmp = new ArrayList<>();
List<Integer> thisLayer = new ArrayList<>();
for(int i = 0 ; i < tmp.size() ; i++ ){
//collect this layer's value
thisLayer.add(tmp.get(i).val);
//collect next layer's node
if((tmp.get(i).left != null)){
_tmp.add((tmp.get(i).left));
}
if((tmp.get(i).right != null)){
_tmp.add((tmp.get(i).right));
}
}
collector.add(thisLayer);
return _tmp;
}
}
执行结果的效率能排到60%:
Paste_Image.png
网友评论