首页 > 代码库 > 二叉树层次遍历

二叉树层次遍历

http://www.lintcode.com/zh-cn/problem/binary-tree-level-order-traversal/#

错误点:queue是抽象的,实例化时,实例成LinkedList

    q.isEmpyt()  不是q.empty()

    入队 q.offer(E)    出队  q.poll()

技术分享
 1 public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
 2         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 3         if(root == null) return result;
 4         Queue<TreeNode> q = new LinkedList<TreeNode>();
 5         q.offer(root);
 6         ArrayList<Integer> arr = null;
 7         while(!q.isEmpty()){
 8             arr = new ArrayList<Integer>();
 9             int num = q.size();
10             for(int i = 0; i <num; i++) {
11                 TreeNode temp = q.poll();
12                 arr.add(temp.val);
13                 if(temp.left != null) q.offer(temp.left);
14                 if(temp.right != null) q.offer(temp.right);
15             }
16             result.add(arr);
17         }
18         return result;
19     }
View Code

 

二叉树层次遍历