import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
// write code here
if(root == null){
return new ArrayList<ArrayList<Integer>>();
}
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
result = traverse(root, 0, result);
return result;
}
public ArrayList<ArrayList<Integer>> traverse(TreeNode root, int deep, ArrayList<ArrayList<Integer>> list){
if(root == null){
return null;
}
//防止数组越界
if(list.size() <= deep){
ArrayList<Integer> curDeepList = new ArrayList<>();
curDeepList.add(root.val);
list.add(curDeepList);
}else{
ArrayList<Integer> oldList = list.get(deep);
oldList.add(root.val);
}
traverse(root.left, deep+1, list);
traverse(root.right, deep+1, list);
return list;
}
}
travel传入树,层数,以及list。