二叉树排序算法

二叉树排序的基本原理:使用第一个元素作为根节点,如果之后的元素比第一个小,则放到左子树,否则放到右子树,之后按中序遍历。

下面实现一个二叉树排序的比较算法,为了操作方便,使用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 }

 

posted @ 2018-01-15 14:51  weller  阅读(18421)  评论(0编辑  收藏  举报