• 摇摆打印二叉树


    问题

      请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

    分析:

      (1)对树进行层次遍历:使用队列

      (2)需要单独记录每一层的序列:两个队列交替使用

    code:

      

    //树节点
    public class TreeNode {
            int val = 0;
            TreeNode left = null;
            TreeNode right = null;
    
            public TreeNode(int val) {
                this.val = val;
    
            }
        }
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
            /*
            层次遍历:队列
            奇数行:左——>右
            偶数行:右->左(奇数行的逆序)
             */
            ArrayList<ArrayList<Integer>> allList = new ArrayList<ArrayList<Integer>>();
            if(pRoot==null){
                return null;
            }
            Queue<TreeNode>[] queue = new Queue[2];
            queue[0] = new ArrayDeque<>();//奇数行
            queue[1] = new ArrayDeque<>();//偶数行
            int count=1; //记录当前到达的层数
            queue[1].add(pRoot);
            while(!queue[0].isEmpty() || !queue[1].isEmpty()){
                ArrayList<Integer> list = new ArrayList<>();
                while(!queue[count%2].isEmpty()){
                    TreeNode temp = queue[count%2].poll();
                    list.add(temp.val);
                    if(temp.left!=null){
                        queue[(count+1)%2].add(temp.left);
                    }
                    if(temp.right!=null){
                        queue[(count+1)%2].add(temp.right);
                    }
                }
           //偶数行:翻转序列
    if(count%2==0){ Collections.reverse(list); } allList.add(list); count++; } return allList; }
  • 相关阅读:
    HDU 2669 Romantic【扩展欧几里德】
    POJ 1061 青蛙的约会【扩展欧几里德】
    求逆元
    扩展欧几里德算法
    HDU 3400 Line belt【三分套三分】
    HDU 2298 Toxophily 【二分+三分】
    006服务监控看板Hystrix Dashboard
    005hystrix.stream信息聚合Turbine
    003客户端负载均衡Ribbon & 短路器Hystrix
    004声明式服务调用Feign & 断路器Hystrix
  • 原文地址:https://www.cnblogs.com/dream-flying/p/12923960.html
Copyright © 2020-2023  润新知