思路:
首先新建一个前序遍历函数,然后,其中参数包括结点、List和深度,如果深度大于list中list的数量,则新加入一个list再取list中的第deep-1个列表 加入root.val的值
class Solution {
List<List<Integer>> list=new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
function(root,1);
return list;
}
public void function(TreeNode root,int deep){
if(root==null) return ;
if(list.size()<deep){
list.add(new ArrayList<Integer>());
}
list.get(deep-1).add(root.val);
function(root.left,deep+1);
function(root.right,deep+1);
}
}