JAVA 按之字形顺序打印二叉树

分别用两个栈存放树的奇数行和偶数行,奇数行自左向右压入孩子,偶数行自右向左压入孩子。
【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; } }



    推荐阅读