• 面试题 32(2):之字形打印二叉树


    import java.util.ArrayList;
    import java.util.Stack;
    /**
     * 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,
     * 第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
     */
    public class ZhiZiXingDaYinErChaShu {
        public static void main(String[] args) {
            TreeNode15 node15 = new TreeNode15(8);
            node15.left = new TreeNode15(6);
            node15.right = new TreeNode15(10);
            Solution15 solution15 = new Solution15();
            ArrayList<ArrayList<Integer>> resultList = solution15.Print(node15);
            for(ArrayList<Integer> list : resultList){
                for(Integer num : list){
                    System.out.print(num+",");
                }
                System.out.println();
            }
        }
    }
    
    
    
    class TreeNode15 {
        int val = 0;
        TreeNode15 left = null;
        TreeNode15 right = null;
    
        public TreeNode15(int val) {
            this.val = val;
    
        }
    }
    
    class Solution15{
        public ArrayList<ArrayList<Integer>> Print(TreeNode15 pRoot) {
            ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
            if(pRoot == null)
                return listAll;
            Stack<TreeNode15>[] stacks = new Stack[2];
            stacks[0]=new Stack<TreeNode15>();
            stacks[1]=new Stack<TreeNode15>();
            int current=0,next=1;
            stacks[0].push(pRoot);
            ArrayList<Integer> list = new ArrayList<Integer>();
            while(stacks[0].size()!=0 || stacks[1].size()!=0){
                TreeNode15 treeNode15 = stacks[current].pop();
                list.add(treeNode15.val);
                if(current==0){
                    if(treeNode15.left!=null){
                        stacks[next].push(treeNode15.left);
                    }
                    if(treeNode15.right!=null){
                        stacks[next].push(treeNode15.right);
                    }
                }else{
                    if(treeNode15.right!=null){
                        stacks[next].push(treeNode15.right);
                    }
                    if(treeNode15.left!=null){
                        stacks[next].push(treeNode15.left);
                    }
                }
                if(stacks[current].size()==0){
                    listAll.add(list);
                    list=new ArrayList<Integer>();
                    current=1-current;
                    next=1-next;
                }
            }
            return listAll;
        }
    }
  • 相关阅读:
    Swift
    ios高质量博客
    Swift
    UML建模
    Swift
    Swift
    IIS建立.net framework4 应用程序池HTTP 错误 500.21
    zz entity framework vs linq to sql
    zz部署wcf iis
    zzIIS站点中部署WCF项目
  • 原文地址:https://www.cnblogs.com/Allen-win/p/8757805.html
Copyright © 2020-2023  润新知