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] ]
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { /**This is a simple problem.<br> * * @param root --the root node of a tree * @return List of value of each level * @author Averill Zheng * @version 2016-06-03 * @since JDK 1.7 */ public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer> > result = new ArrayList<List<Integer>>(); if(root != null){ Queue<TreeNode> topLevel = new LinkedList<TreeNode>(); topLevel.add(root); while(topLevel.peek() != null){ Queue<TreeNode> nextLevel = new LinkedList<TreeNode>(); List<Integer> value = new ArrayList<Integer>(); while(topLevel.peek() != null){ TreeNode node = topLevel.poll(); value.add(node.val); if(node.left != null) nextLevel.add(node.left); if(node.right != null) nextLevel.add(node.right); } result.add(value); topLevel = nextLevel; } } return result; } }