二叉树的层次遍历算法设计
设计二叉树的层次遍历算法
二叉树层次遍历的结果应该为:
62,15,68,12,46,65,79,35,57
算法设计如下
/*
* 二叉树的层次遍历算法设计
* */
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<List<Integer>> wrapList = new LinkedList<List<Integer>>();
if(root == null) return wrapList;
queue.offer(root);
while(!queue.isEmpty()){
int levelNum = queue.size();
List<Integer> subList = new LinkedList<Integer>();
for(int i=0; i<levelNum; i++) {
if(queue.peek().leftChild != null) queue.offer(queue.peek().leftChild);
if(queue.peek().rightChild != null) queue.offer(queue.peek().rightChild);
subList.add(queue.poll().