Java-二叉樹演算法

來源:互聯網
上載者:User

標籤:二叉樹   演算法   java   

二叉樹演算法的定序: 

 1、選擇第一個元素作為根節點 

 2、之後如果元素大於根節點放在右子樹,如果元素小於根節點,則放在左子樹

 3、最後按照中序遍曆的方式進行輸出,則可以得到排序的結果(左->根->右)

二叉樹演算法的核心類,此類只提供了添加和列印輸出的方法

package com.lym.binaryTree;/** * 二叉樹演算法的定序:  * 1、選擇第一個元素作為根節點  * 2、之後如果元素大於根節點放在右子樹,如果元素小於根節點,則放在左子樹 * 3、最後按照中序遍曆的方式進行輸出,則可以得到排序的結果(左->根->右) *  * @author Administrator *  */public class BinaryTree {private Node root;// 根節點// 添加節點,提供外部存取public void add(int data) {if (root == null) {root = new Node(data);} else {root.addNode(data);}}// 輸出節點,提供外部存取public void print() {if (root != null) {root.printNode();}}// 樹枝節點class Node {private Node leftNode;private Node rightNode;private int data;public Node(int data) {this.data = data;}// 添加節點public void addNode(int data) {if (this.data > data) {// 添加在左面if (this.leftNode == null) {this.leftNode = new Node(data);} else {this.leftNode.addNode(data);}} else if (this.data <= data) {if (this.rightNode == null) {this.rightNode = new Node(data);} else {this.rightNode.addNode(data);}}}// 輸出所有節點//中序遍曆public void printNode() {if (this.leftNode != null) {this.leftNode.printNode();}System.out.print(this.data + " ");//輸出語句放最後就是後續遍曆if (this.rightNode != null) {this.rightNode.printNode();}}}}

二叉樹的測試類別

package com.lym.binaryTree;/** * 二叉樹測試類別 *  * @author Administrator * */public class BinaryTreeDemo {public static void main(String[] args) {BinaryTree bt = new BinaryTree();bt.add(3);bt.add(5);bt.add(2);bt.add(1);bt.add(4);bt.add(8);bt.add(10);bt.add(13);bt.add(6);bt.add(9);bt.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.