java建立二叉樹並遞迴遍曆二叉樹

來源:互聯網
上載者:User

標籤:

二叉樹類代碼:

package binarytree;import linkqueue.LinkQueue;public class BinaryTree {class Node{public Object data;public Node lchild;public Node rchild;public Node(Object data){this.data = data;this.lchild = null;this.rchild = null;}}//根節點private Node root = null;private Node node = null;/** * 建立樹 *  * 以完全二叉樹的格式來建立(子樹不存在的用0填充), * 對完全二叉樹中每一個節點從0開始進行編號, * 那麼第i個節點的左孩子的編號為2*i+1,右孩子為2*i+2。 *  * */void createTree(String strtree){LinkQueue lQueue = new LinkQueue();lQueue.initQueue();/** * 完全二叉樹中第i層的結點的個數最多為第1到i-1層上所有節點的個數和 * 所以父節點的個數最多為N-1個,N表示節點個數 * */for(int parentIndex =0; parentIndex<strtree.split(" ").length/2;parentIndex++){if(root == null){root= new Node(strtree.split(" ")[parentIndex]);//左孩子root.lchild = new Node(strtree.split(" ")[parentIndex*2+1]);lQueue.enQueue(root.lchild);//右孩子root.rchild = new Node(strtree.split(" ")[parentIndex*2+2]);lQueue.enQueue(root.rchild);}else{if(!lQueue.isEmpty() && parentIndex*2+1<strtree.split(" ").length)//隊列不空{node = (Node) lQueue.deQueue();if(parentIndex*2+1<strtree.split(" ").length){//左孩子node.lchild = new Node(strtree.split(" ")[parentIndex*2+1]);lQueue.enQueue(node.lchild);}if(parentIndex*2+2<strtree.split(" ").length){//右孩子node.rchild = new Node(strtree.split(" ")[parentIndex*2+2]);lQueue.enQueue(node.rchild);}}else{return;}}}}/** * 先序遍曆二叉樹 * */void preOrderTraverse(Node node){if(node == null){return;}visit(node);preOrderTraverse(node.lchild);preOrderTraverse(node.rchild);}/** * 中序遍曆二叉樹 * */void inOrderTraverse(Node node){if(node == null){return;}inOrderTraverse(node.lchild);visit(node);inOrderTraverse(node.rchild);}/** * 後序遍曆二叉樹 * */void postOrderTraverse(Node node){if(node == null){return;}postOrderTraverse(node.lchild);postOrderTraverse(node.rchild);visit(node);}/** * 列印二叉樹 * */public void print(){System.out.print("先序遍曆:");preOrderTraverse(root);System.out.print("\n中序遍曆:");inOrderTraverse(root);System.out.print("\n後序遍曆:");postOrderTraverse(root);}/** * 訪問節點 * */private void visit(Node node){if(!node.data.equals("0")){System.out.print(node.data+" ");}}}

測試代碼(以資料結構中運算式a+b*(c-d)-e/f為例):

package binarytree;public class BinaryTreeMain {public static void main(String[] args) {BinaryTree binaryTree = new BinaryTree();String strtree="- + / a * e f 0 0 b - 0 0 0 0 0 0 0 0 0 0 c d";//0表示沒有值的位置binaryTree.createTree(strtree);binaryTree.print();}}

 運行結果:

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.