// 之字形打印二叉树
public void printTree(TreeNode root){
if(root == null)
return ;
Stack<TreeNode> odd = new Stack<TreeNode>(); // 存储奇数层节点
Stack<TreeNode> even = new Stack<TreeNode>(); // 存储偶数层节点
odd.push(root);
while(!odd.isEmpty() || !even.isEmpty()){
if(!odd.isEmpty()){
while(!odd.isEmpty()){
TreeNode tmp = odd.pop();
System.out.printf(tmp.val + " ");
if(tmp.left != null) even.push(tmp.left);
if(tmp.right != null) even.push(tmp.right);
}
}else if(!even.isEmpty()){
while(!even.isEmpty()){
TreeNode tmp = even.pop();
System.out.printf(tmp.val + " ");
if(tmp.right != null) odd.push(tmp.right);
if(tmp.left != null) odd.push(tmp.left);
}
}
System.out.println();
}
}
网友评论