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,null,null,15,7],
一刷
题解:DFS,并在子函数内传入level表示加入哪一层list
/**
* Definition for a binary tree node.
* 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;
level(root, 0, res);
return res;
}
public void level(TreeNode root, int level, List<List<Integer>> res){
if(root == null) return;
if(level>=res.size()) res.add(new ArrayList<>());
res.get(level).add(root.val);
level(root.left, level+1, res);
level(root.right, level+1, res);
}
}