把二叉树打印成多行
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
分析
层次遍历问题。可以使用递归,为每一层开辟一个List,依次加入每一层级的节点。
实现
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
depthNode(pRoot, 0);
return result;
}
private void depthNode(TreeNode root, int depth){
if(root == null) return ;
if(result.size() < depth + 1){
result.add(new ArrayList<Integer>());
}
result.get(depth).add(root.val);
depthNode(root.left, depth + 1);
depthNode(root.right, depth + 1);
}