把二叉树打印成多行


从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行


解题思路

使用前序遍历结点,记录深度,同一深度下添加结点

public class Solution {
    ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        depth(pRoot, 1, list);
        return list;
    }
    
    void depth(TreeNode node, int depth, ArrayList<ArrayList<Integer>> list) {
        if(node == null) {
            return;
        }
        if(depth > list.size()) {
            list.add(new ArrayList<Integer>());
        }
        list.get(depth - 1).add(node.val);
        depth(node.left, depth + 1, list);
        depth(node.right, depth + 1, list);
    }
}

原文地址:https://www.cnblogs.com/Yee-Q/p/14203193.html