二叉樹基礎之按層打印


轉載請注明原文地址: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;
    }

 

 

                                                              

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM