思路:递归,扩容
增加一个deep参数,内部list数量与deep相同,每个深度对应一个list
根节点添加到list(deep-1),然后分别对其左右子树递归求每层的节点,深度每到一个孩子+1
import java.util.ArrayList; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> list=new ArrayList<>(); depth(pRoot,1,list); return list; } public void depth(TreeNode root,int deep,ArrayList<ArrayList<Integer>> list){ if(root==null){ return; } if(deep>list.size()){ list.add(new ArrayList<>()); } list.get(deep-1).add(root.val); depth(root.left,deep+1,list); depth(root.right,deep+1,list); } }