按之字形顺序打印二叉树

时间:2019-03-19
本文章向大家介绍按之字形顺序打印二叉树,主要包括按之字形顺序打印二叉树使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

思路:两个栈s1和s2,遍历s1时按左到右顺序在s2存放子树根节点,遍历s2时按从右到左顺序在s1存放子树根节点

public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
        if(pRoot == null) return listAll;
        Stack<TreeNode> s1 = new Stack();//栈
        Stack<TreeNode> s2 = new Stack();
       
        TreeNode p = null;
       
        s1.push(pRoot);
        while(!s1.isEmpty() || !s2.isEmpty()){
            ArrayList<Integer> list = new ArrayList<>();
            while(!s1.isEmpty()){
                p = s1.pop();
                list.add(p.val);
                if(p.left != null)s2.push(p.left);
                if(p.right != null)s2.push(p.right);
            }
            if(!list.isEmpty())listAll.add(list);
            list = new ArrayList<>();
            while(!s2.isEmpty()){
                p = s2.pop();
                list.add(p.val);
                if(p.right != null)s1.push(p.right);
                if(p.left != null)s1.push(p.left);
            }
            if(!list.isEmpty())listAll.add(list);
        }
        return listAll;
       

    }

}