畢業了-java二叉樹層次遍曆演算法

來源:互聯網
上載者:User

標籤:rgs   使用   com   void   技術分享   offer   move   stat   add   

/***************************************      * 時間:2017年6月23日       * author:lcy      * 內容:二叉樹的層次遍曆       * 需要藉助隊列這個資料結構,直接import就可以了 *     1.首先將根節點放入隊列中。        2.當隊列為非空時,迴圈執行步驟3到步驟5,否則執行6;        3.出隊列取得一個結點,訪問該結點;        4.若該結點的左子樹為非空,則將該結點的左子樹入隊列;        5.若該結點的右子樹為非空,則將該結點的右子樹入隊列;        6.結束。 ***************************************/    import java.util.ArrayDeque;     import java.util.Queue;    public class BinTree {    private char date;    private BinTree lchild;   //左孩子    private BinTree rchild;   //右孩子        private BinTree(char c ){        date = c;    }         public static void BFSOrder(BinTree T)    {        if(T==null) return ;        Queue<BinTree> queue = new ArrayDeque<BinTree>();            //隊列小知識:使用offer和poll優於add和remove之處在於它們傳回值可以判斷成功與否,而不拋出異常            queue.offer(T);              //演算法1:根結點進入隊列        while(!queue.isEmpty())      //演算法2:若隊列非空,迴圈執行步驟 3-5,否則執行步驟6        {            T=queue.poll();          //演算法3:將一個結點出隊列,並訪問該結點            System.out.print(T.date);            if(T.lchild!=null)       //演算法4:若該結點的左子樹為非空,則將該結點的左孩子結點入隊列;                queue.offer(T.lchild);            if(T.rchild!=null)       //演算法5:若該結點的左子樹為非空,則將該結點的右孩子結點入隊列;                queue.offer(T.rchild);            }        //步驟6結束    }                public static void main(String[] args) {         BinTree b1 = new BinTree(‘a‘);         BinTree b2 = new BinTree(‘b‘);         BinTree b3 = new BinTree(‘c‘);         BinTree b4 = new BinTree(‘d‘);         BinTree b5 = new BinTree(‘e‘);         BinTree b6 = new BinTree(‘f‘);         BinTree b7 = new BinTree(‘g‘);            /**         *      a          *    /            *   b     c         *  / \   /          * d   e f   g         */        b1.lchild = b2;        b1.rchild = b3;        b2.lchild = b4;        b2.rchild = b5;        b3.lchild = b6;        b3.rchild = b7;        System.out.println(12121);        BinTree.BFSOrder(b1);        System.out.println();            }}
測試結果

 

 

 

畢業了-java二叉樹層次遍曆演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.