剑指offer第二版-32.3.之字形打印二叉树

本系列导航:剑指offer(第二版)java实现导航帖

面试题32.3:之字形打印二叉树

题目要求:
请实现一个函数按照之字形打印二叉树。即第一层从左到右打印,第二层从右到左打印,第三层继续从左到右,以此类推。

解题思路:
第k行从左到右打印,第k+1行从右到左打印,可以比较容易想到用两个栈来实现。
另外要注意,根据是从左到右还是从右到左访问的不同,压入左右子节点的顺序也有所不同。

package structure;
import java.util.LinkedList;
import java.util.Queue;
/**
 * Created by ryder on 2017/6/12.
 * 树节点
 */
public class TreeNode {
    public T val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(T val){
        this.val = val;
        this.left = null;
        this.right = null;
    }
}
package chapter4;
import structure.TreeNode;
import java.util.Stack;
/**
 * Created by ryder on 2017/7/18.
 * 之字形打印二叉树
 */
public class P176_printTreeInSpecial {
    public static void printTreeInSpeical(TreeNode root){
        if(root==null)
            return;
        Stack> stack1 = new Stack<>();
        Stack> stack2 = new Stack<>();
        TreeNode temp;
        stack1.push(root);
        while(!stack1.isEmpty() || !stack2.isEmpty()){
            if(!stack1.isEmpty()) {
                while (!stack1.isEmpty()) {
                    temp = stack1.pop();
                    System.out.print(temp.val);
                    System.out.print('\t');
                    if (temp.left != null)
                        stack2.push(temp.left);
                    if (temp.right != null)
                        stack2.push(temp.right);
                }
            }
            else {
                while (!stack2.isEmpty()) {
                    temp = stack2.pop();
                    System.out.print(temp.val);
                    System.out.print('\t');
                    if (temp.right != null)
                        stack1.push(temp.right);
                    if (temp.left != null)
                        stack1.push(temp.left);
                }
            }
            System.out.println();
        }
    }
    public static void main(String[] args){
        //            1
        //          /   \
        //         2     3
        //       /  \   / \
        //      4    5 6   7
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        printTreeInSpeical(root);
    }
}

运行结果

1111

你可能感兴趣的:(剑指offer第二版-32.3.之字形打印二叉树)