二叉樹遍曆Java實現

來源:互聯網
上載者:User

標籤:

 

【僅貼代碼及測試結果】

-------------------BinaryTree.java------------------------------

class Tree<E>{    E element;    Tree<E> lChild;    Tree<E> rChild;    public Tree(E e){        element = e;    }}public class BinaryTree {    /**     * 樹形如下:     *         1     *     /      *    2   3     *    \   /      *     4  5  6     */        public static void main(String[] args) {        Tree<Integer> n1 = new Tree<Integer>(1);        Tree<Integer> n2 = new Tree<Integer>(2);        Tree<Integer> n3 = new Tree<Integer>(3);        Tree<Integer> n4 = new Tree<Integer>(4);        Tree<Integer> n5 = new Tree<Integer>(5);        Tree<Integer> n6 = new Tree<Integer>(6);        System.out.println("Construct the tree...");        n2.rChild=n4;        n3.lChild=n5;        n3.rChild=n6;        n1.lChild=n2;        n1.rChild=n3;                System.out.println("列印先序遍曆結果:");        firstOrder(n1);        System.out.println("\n列印中序遍曆結果:");        midOrder(n1);        System.out.println("\n列印後序遍曆結果:");        lastOrder(n1);    }        public static <E> void firstOrder(Tree<E> root){        if(root!=null){            System.out.print(root.element+" ");            firstOrder(root.lChild);            firstOrder(root.rChild);        }    }    public static <E> void lastOrder(Tree<E> root){        if(root!=null){            lastOrder(root.lChild);            lastOrder(root.rChild);            System.out.print(root.element+" ");        }    }    public static <E> void midOrder(Tree<E> root){        if(root!=null){            midOrder(root.lChild);            System.out.print(root.element+" ");            midOrder(root.rChild);        }    }}

輸出結果:

Construct the tree...列印先序遍曆結果:1 2 4 3 5 6 列印中序遍曆結果:2 4 1 5 3 6 列印後序遍曆結果:4 2 5 6 3 1 

 

二叉樹遍曆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.