traverse the binary tree from left to right, from top to bottom:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
List<TreeNode> level = new ArrayList<>();
level.add(root);
while(true){
if(level.isEmpty() || level.get(0) == null)
break;
List <TreeNode> nextlevel = new ArrayList<>();
List <Integer> curnum = new ArrayList<>();
for(int i = 0; i < level.size(); ++i){
TreeNode node = level.get(i);
curnum.add(node.val);
if(node.left != null) nextlevel.add(node.left);
if(node.right != null) nextlevel.add(node.right);
}
res.add(curnum);
level = nextlevel;
}
return res;
}
}