题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
分析
利用递归的方法进行先序遍历,传递深度,递归深入一层扩容一层数组,先序遍历又保证了同层节点按从左到右入数组
贴出代码
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 depth, ArrayList<ArrayList<Integer>> list){
if(root == null){
return;
}
if(depth > list.size()){
list.add(new ArrayList<Integer>());
}
list.get(depth - 1).add(root.val);
depth(root.left, depth + 1, list);
depth(root.right, depth + 1, list);
}
}