题目:
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}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]解答:
普通的水平遍历,是使用一个队列,把节点依次装入,然后依次取出即可。这里,需要区分出在哪一行,因此,节点装入时要带上level信息。
代码:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public class NewNode{
TreeNode node;
int level;
NewNode(TreeNode m,int l){
node = m;
level = l;
}
}
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null) return new Vector<List<Integer> >();
List<List<Integer> > result = new Vector<List<Integer> >();
List<Integer> cur = new Vector<Integer>();
Queue<NewNode> nodeQueue = new LinkedList<NewNode>();
int lastLevel = 0;
nodeQueue.add(new NewNode(root,0));
while(!nodeQueue.isEmpty()){
NewNode head = nodeQueue.poll();
if(head.level > lastLevel){
result.add(cur);
cur = new Vector<Integer>();
lastLevel = head.level;
}
cur.add(head.node.val);
if(head.node.left != null){
nodeQueue.offer(new NewNode(head.node.left,lastLevel+1));
}
if(head.node.right != null){
nodeQueue.offer(new NewNode(head.node.right,lastLevel+1));
}
}
// last level
result.add(cur);
return result;
}
}