分别用两个栈存放树的奇数行和偶数行,奇数行自左向右压入孩子,偶数行自右向左压入孩子。
【JAVA 按之字形顺序打印二叉树】
import java.util.LinkedList;
import java.util.Stack;
/**
* Created by Administrator on 2018/3/7.
*/
public class zhiPrint {
public void print(TreeNode root){
if(root==null)
return;
Stack s1 = new Stack<>();
//存放奇数行
Stack s2 = new Stack<>();
//存放偶数行
s1.push(root);
while(!s1.isEmpty() || !s2.isEmpty()){
while (!s1.isEmpty()) {//弹出奇数行所有元素
TreeNode node = s1.pop();
System.out.print(node.element+" ");
if (s1.isEmpty())//判断该行是否结束
System.out.println();
if (node.left != null)
s2.push(node.left);
//先左child再右child压入偶数行的栈
if (node.right != null)
s2.push(node.right);
}
while (!s2.isEmpty()) {//弹出偶数行所有元素
TreeNode node = s2.pop();
System.out.print(node.element+" ");
if (s2.isEmpty())
System.out.println();
if (node.right != null)
s1.push(node.right);
//先右child再左child压入奇数行的栈
if (node.left != null)
s1.push(node.left);
}
}
}
public static void main(String... args){
LinkedList q = new LinkedList<>();
//用队列构建一棵完全二叉树,节点从1至15
int i = 1;
TreeNode root = new TreeNode(i++);
q.add(root);
while (!q.isEmpty()&&i<=15){
TreeNode lchild = new TreeNode(i++);
TreeNode rchild = new TreeNode(i++);
TreeNode node = q.poll();
node.left = lchild;
node.right = rchild;
q.add(node.left);
q.add(node.right);
}
//之字打印
new zhiPrint().print(root);
}
}
class TreeNode {
Object element;
TreeNode left;
TreeNode right;
public TreeNode(int id){
element = (Object)id;
}
}
推荐阅读
- Integer常量池结合源码解析
- Java基础|Java 打印空心等腰三角形(方法2)
- gradle 每次运行都会下载依赖的解决办法
- 使用vector代替数组
- 如何获取ResultSet的行数和列数
- Java 时间戳格式化
- Java基础|Android开发——JVM、Dalvik以及ART的区别
- XML|XML报文转Map
- Java 8 时间,字符串和Long时间戳互转
- JAVA基础|JAVA基础(TreeMap键是Student值是String案例)