按之字形顺序打印二叉树

时间:2021-02-26 17:27:56


class Solution{
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(pRoot==null)//边界条件
return result;
ArrayList<TreeNode> ele = new ArrayList<TreeNode>();//保存每一层的树节点
ele.add(pRoot);
boolean flag = true;//标记位
while(!ele.isEmpty()){
ArrayList<Integer> temp = new ArrayList<Integer>();//每一层树节点的值
int len = ele.size();
for(int i = 0;i<len;i++){
TreeNode node = ele.get(0);
if(node.left!=null)
ele.add(node.left);
if(node.right!=null)
ele.add(node.right);
if(flag)
temp.add(node.val);//尾部追加类似于队列
else
temp.add(0,node.val);//从头部添加,类似于栈
ele.remove(0);
}
flag ^=true;//改变放入方向
result.add(temp);
}
return result;
}
}