从上往下打印二叉树 该题与之字形打印二叉树类似 都是利用两个栈去实现
import java.util.*;
/*
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) {
if(pRoot==null)
{return new ArrayList<ArrayList<Integer>>();}
Stack<TreeNode> stack1=new Stack<TreeNode>();
stack1.push(pRoot);
ArrayList<ArrayList<Integer> > arr1=new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> arr2=new ArrayList<Integer>();
arr2.add(pRoot.val);
//添加头元素
arr1.add(arr2);
while(stack1.isEmpty()!=true)
{
Stack<TreeNode> stack2=new Stack<TreeNode>();
while(stack1.isEmpty()!=true)
{
TreeNode b=stack1.pop();
if(b.left!=null)
{
stack2.push(b.left);
}
if(b.right!=null)
{
stack2.push(b.right);
}
}
ArrayList<Integer> arr3=new ArrayList<Integer>();
while(stack2.isEmpty()!=true)
{
TreeNode a=stack2.pop();
arr3.add(a.val);
stack1.push(a);
}
if(stack1.isEmpty()!=true)
{ Collections.reverse(arr3);
arr1.add(arr3);
}
}
return arr1;
}
}