首页 > 代码库 > Binary Tree Level Order Traversal

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},

    3
   /   9  20
    /     15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

方法

树的层次遍历,使用Queue,并用一个计数器来标记下一层的元素个数。
PS:其实可以不用计数器,可以用队列元素的个数来统计。
    public List<List<Integer>> levelOrder(TreeNode root) {
    	List<List<Integer>> list = new ArrayList<List<Integer>>();
    	
    	if (root == null) {
    		return list;
    	}
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int count = 1;
        while (!queue.isEmpty()) {
        	int len = count;
        	count = 0;
        	List<Integer> subList = new ArrayList<Integer>();
        	for(int i = 0; i < len; i++) {
        		TreeNode curNode = queue.poll();
        		subList.add(curNode.val);
        		if (curNode.left != null) {
        			queue.offer(curNode.left);
        			count++;
        		}
        		if (curNode.right != null) {
        			queue.offer(curNode.right);
        			count++;
        		}
        	}
        	list.add(subList);
        }
        return list;
    }