题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
http://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
import java.util.*;
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
Queue<Integer> level = new LinkedList<>();
queue.add(root);
level.add(1);
int curLevel = level.peek();
ArrayList<Integer> list = new ArrayList<>();
while(!queue.isEmpty()){
TreeNode poll = queue.poll();
Integer levelPoll = level.poll();
if(poll!=null&&levelPoll!=null){
if(curLevel<levelPoll){
result.add(list);
list = new ArrayList<>();
curLevel = levelPoll;
}
list.add(poll.val);
levelPoll++;
queue.add(poll.left);
level.add(levelPoll);
queue.add(poll.right);
level.add(levelPoll);
}
}
result.add(list);
return result;
}
}