软件编程
位置:首页>> 软件编程>> java编程>> Java基于二叉查找树实现排序功能示例

Java基于二叉查找树实现排序功能示例

作者:冷豪  发布时间:2022-09-04 21:50:52 

标签:Java,二叉查找树,排序

本文实例讲述了Java基于二叉查找树实现排序功能。分享给大家供大家参考,具体如下:


/**
* 无论排序的对象是什么,都要实现Comparable接口
*
* @param <T>
*/
public class BinaryNode<T extends Comparable<T>> {
 private static int index = 0; // 排序下标
 private static int len = 0; // 最大数组长度
 private T t; // 根节点
 private BinaryNode<T> left; // 左侧叶子节点
 private BinaryNode<T> right; // 右侧叶子节点
 public BinaryNode(T t) {
   len++;
   this.t = t;
 }
 /**
  * 往一颗书中插入值,在本质上都通过根节点一层层的判断。
  * 如果根节点不存在则新建节点
  * 如果根节点存在则判断应该在左侧还是在右侧插入,通常是左小右大
  *
  * @param t
  */
 public void insert(T t) {
   if (this.t.compareTo(t) > 0) {
     if (this.left == null) {
       BinaryNode<T> node = new BinaryNode<T>(t);
       this.left = node;
     } else {
       this.left.insert(t);
     }
   } else {
     if (this.right == null) {
       BinaryNode<T> node = new BinaryNode<T>(t);
       this.right = node;
     } else {
       this.right.insert(t);
     }
   }
 }
 /**
  * 调用私有方法
  *
  * @return
  */
 public Comparable<?>[] order() {
   Comparable<?>[] os = new Comparable[len];
   order(this, os);
   return os;
 }
 /**
  * 利用中序遍历查找整颗树
  *
  * @param bn
  * @param os
  */
 private void order(BinaryNode<T> bn, Comparable<?>[] os) {
   if (bn.left == null) {
     os[index++] = bn.t;
   } else {
     order(bn.left, os);
     os[index++] = bn.t;
   }
   if (bn.right == null) {
     return;
   } else {
     order(bn.right, os);
   }
 }
}

希望本文所述对大家java程序设计有所帮助。

来源:http://www.cnblogs.com/learnhow/p/6047421.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com