欢迎光临散文网 会员登陆 & 注册

java模拟二叉树实现排序

2022-08-05 16:06 作者:虚云幻仙  | 我要投稿

/**
* 使用树形结构--二叉树实现排序
* 二叉树为结点的度最大为2的树,每个结点最多有两个子结点
* 二叉排序树的定义:1.根结点的左子树的值小于根结点 2.根结点的右子树的值大于根结点 3.左右子树也各为一颗二叉排序树
* 二叉排序树的中序遍历的结果为一个有序的集合
*/

public class SortByBinaryTree<E extends Integer> {
   //模拟二叉排序树   对Integer类型进行排序
   private static final class Node<E extends Integer>{
       //泛型类定义E小于等于Integer 类内使用E不再声明extends
       E item;
       //存放元素
       Node<E> left;
       //左子树
       Node<E> right;
       //右子树
       public Node(E item, Node<E> left, Node<E> right) {
           this.item = item;
           this.left = left;
           this.right = right;
       }
   }

   Node<E> root;
   //类中仅记录根结点,每次操作通过根结点递进向下调用
   public void add(E e){
       if (e==null)return;
       //返回类型void的方法内return不加参数会结束方法
       if (root==null){
           root = new Node<>(e,null,null);
       }else {
           Node<E> n = getParentNode(e);
           if (n==null)return;
           if (e.intValue() < n.item.intValue()) {
               //E extends Integer 所以可以使用.intValue()
               n.left = new Node<>(e, null, null);
           } else {
               n.right = new Node<>(e, null, null);
           }
       }
   }
   private Node<E> getParentNode(E e){
       int eInt = e.intValue();
       int nInt;
       for (Node<E> n = root;eInt != (nInt=n.item.intValue());){
           //在判定条件中赋值
           if (eInt < nInt){
               if (n.left==null){
                   return n;
               }else {
                   n=n.left;
               }
           } else {
               if (n.right==null){
                   return n;
               }else {
                   n=n.right;
               }
           }
       }
       return null;
       //重复元素不添加
   }

   public void traversal(){
       //遍历traversal
       if (root==null){
           System.out.println("当前无元素");
           return;
       }
       traversal(root);
   }
   private void traversal(Node<E> n){
       if (n!=null){
           traversal(n.left);
           System.out.print(n.item+", ");
           traversal(n.right);
       }
   }

   public static void main(String[] args) {
       Random r = new Random();
       Integer[] arr = new Integer[10];
       for (int i = 0;i<10;i++){
           arr[i] = r.nextInt(40);
       }
       SortByBinaryTree<Integer> sort = new SortByBinaryTree<>();
       for (Integer i:arr){
           sort.add(i);
       }
       System.out.println(Arrays.toString(arr));
       //打印原数组,结果为[28, 3, 14, 36, 12, 25, 15, 5, 37, 22]
       sort.traversal();
       //排序结果为3,5,12,14,15,22,25,28,36,37,
   }
}

java模拟二叉树实现排序的评论 (共 条)

分享到微博请遵守国家法律