二叉樹排序的基本原理:使用第一個元素作為根節點,如果之后的元素比第一個小,則放到左子樹,否則放到右子樹,之后按中序遍歷。
下面實現一個二叉樹排序的比較算法,為了操作方便,使用Integer類完成。
public final class Integer extends Number implements Comparable<Integer>
我們可以看到Integer類實現了Comparable接口,所以可用Integer實例化Comparable接口對象。
1 class BinaryTree{ 2 class Node{ //聲明一個節點類 3 private Comparable data; //節點的數據類型為Comparable 4 private Node left; //保存左子樹 5 private Node right; //保存右子樹 6 public Node(Comparable data){ //構造函數 7 this.data = data; 8 } 9 public void addNode(Node newNode){ 10 //確定是放在左子樹還是右子樹 11 if(newNode.data.compareTo(this.data)<0){ //新節點值小於當前節點 12 if(this.left == null){ 13 this.left = newNode; //左子樹為空的話,新節點設為左子樹 14 }else{ 15 this.left.addNode(newNode); //否則繼續向下判斷 16 } 17 }else{ //新節點的值大於或等於當前節點 18 if(this.right == null){ 19 this.right = newNode; 20 }else{ 21 this.right.addNode(newNode); 22 } 23 } 24 } 25 26 public void printNode(){ //采用中序遍歷 27 if(this.left != null){ //如果不為空先輸出左子樹 28 this.left.printNode(); 29 } 30 System.out.print(this.data+"\t"); //輸出當前根節點 31 if(this.right != null){ //輸出右子樹 32 this.right.printNode(); 33 } 34 } 35 } 36 private Node root; //表示根元素 37 38 public void add(Comparable data){ //向二叉樹中插入元素 39 Node newNode = new Node(data); 40 if(root == null){ //沒有根節點 41 root = newNode; 42 }else{ 43 root.addNode(newNode); //判斷放在左子樹還是右子樹 44 } 45 } 46 47 public void print(){ 48 root.printNode(); //根據根節點輸出 49 } 50 } 51 52 public class TestBinaryTreeSort { 53 public static void main(String args[]){ 54 BinaryTree bt = new BinaryTree(); 55 bt.add(3); 56 bt.add(5); 57 bt.add(4); 58 bt.add(8); 59 bt.add(7); 60 bt.add(8); 61 bt.add(1); 62 bt.print(); 63 } 64 }
![]()
