• 二叉树基础之按层打印


     

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6605916.html 

    (Java中栈、队都可以用LinkedList来实例化,栈的方法:push()/pop();队的方法:offer()/poll())

     

          二叉树的按层打印==两个指针last和newlast:出队的时候把左右儿子入队,同时令newlast保存最新入队的结点当出队的结点为last时,说明这一层遍历完毕,此时队列中存放的是下一层的结点,newlast指向下一层的最后结点位置,所以令last=newlast;继续出队遍历,此时遍历的是新的一层了

    复制代码
     public int[][] printTree(TreeNode root) {
            if(root==null){
                return null;
            }
            //用双层ArrayList暂存按层遍历的结果
            ArrayList<ArrayList<Integer>> nodes = new ArrayList<ArrayList<Integer>>();
            //结点队列
            LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
            queue.offer(root);
            //last记录层的最后结点
            TreeNode last=root;
            //newlast跟踪最新入队结点
            TreeNode newlast=null;
            TreeNode curr=null;
            //每层用一个ArrayList暂存
            ArrayList<Integer> levelnodes=new ArrayList<Integer>();
            
            while(!queue.isEmpty()){   
                //弹出队首,加到当前层ArrayList中
                curr=queue.poll();
                levelnodes.add(curr.val);
                //把左右儿子入队,newlast跟踪新入队的结点
                if(curr.left!=null){
                    newlast=curr.left;
                    queue.offer(newlast);
                }
                if(curr.right!=null){
                    newlast=curr.right;
                    queue.offer(newlast);
                }
                //判断当前出队的元素是否为last,即当前层最后结点。是则更新last指向下一层最后结点,并把当前层结果加到双重list去。
                //然后重新创建一个ArrayList存放下一层的结点
                if(curr==last){
                    last=newlast;
                    nodes.add(levelnodes);
                    levelnodes=new ArrayList<Integer>();
                }
            }
            //根据双重链表大小得到树的层次数
            int depth=nodes.size();
            //创建不定长的二维数组,行数为层数,列数不确定
            int[][] res=new int[depth][];
            int i=0;
            for(ArrayList<Integer> list:nodes){
                //双重链表的一个元素是一个存放了一层结点的ArrayList,遍历它得到一个一维数组
                int[] level=new int[list.size()];
                int j=0;
                for(Integer integer:list){
                    level[j++]=integer;
                }
                //然后把该一维数组赋值给不定长二维数组的行头,得到一层结点
                res[i++]=level;
            }   
            return res;
        }
    复制代码

                                                                  

  • 相关阅读:
    spring boot单元测试之七:用mockmvc模拟session(spring boot 2.4.3)
    spring boot单元测试之六:用mockmvc模拟cookie(spring boot 2.4.3)
    sql join 注意事项
    见路不走,即见因果
    presto sql 经典sql 应用
    别拿你的职业去拔高你个人的规格, 让人轻看
    《遥远的救世主》经典台词
    《卜算子·自嘲》
    天道连续剧 丁元英语录
    shell diff + kettle = mail 预警
  • 原文地址:https://www.cnblogs.com/williamjie/p/9478102.html
Copyright © 2020-2023  润新知