**Input:** root = [3,9,20,null,null,15,7]
**Output:** [[3],[9,20],[15,7]]
**Input:** root = [1]
**Output:** [[1]]
**Input:** root = []
**Output:** []
ac1: DFS, preorder traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
helper(root, res, 0);
return res;
}
private void helper(TreeNode root, List<List<Integer>> res, int level) {
if (root == null) return;
if (res.size() <= level) res.add(new ArrayList<Integer>());
res.get(level).add(root.val);
helper(root.left, res, level + 1);
helper(root.right, res, level + 1);
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Queue<TreeNode> q = new LinkedList<TreeNode>();
if (root == null) return res;
q.offer(root);
while (!q.isEmpty()) {
int levelNum = q.size();
List<Integer> tmpList = new ArrayList<Integer>();
for (int i = 0; i < levelNum; i++) {
TreeNode curr = q.poll();
tmpList.add(curr.val);
if (curr.left != null) q.offer(curr.left);
if (curr.right != null) q.offer(curr.right);
}
res.add(tmpList);
}
return res;
}
}