zoukankan      html  css  js  c++  java
  • Java实现二叉排序树

    /**
    * 二叉树排序--将一个整型数组中的元素存进二叉排序树中再查找元素;
    * @author luliangy
    *
    */
    public class BTsort {

    public static void main(String[] args) {

    //自定义一个整型的数组;
    int[] array={19,12,3,22,6,7,21,11,43};

    //创建根节点;

    Node root=new Node(array[0]);

    //依次将数组中的元素插入
    for(int i=1;i<array.length;i++){
    BinarySort(root,array[i]);
    }

    //查找指定的元素;
    if(BinarySerch(root,12)){
    System.out.println("二叉树中存在此元素");
    }else{
    System.out.println("二叉树中不存在该元素");
    }

    //遍历指定的二叉树并输出--采用中序遍历法;
    inOrder(root);

    }

    /**
    * 将指定的元素插入二叉排序树中
    * @param root
    * @param key
    */
    public static void BinarySort(Node root,int key){

    //得到根节点中的元素;
    int value = root.getKey();
    //判断该插入左子树还是右子树;
    if(key<value){//插入柚子树
    if(root.getLeft()==null){
    Node node=new Node(key);
    root.setLeft(node);
    }else{
    BinarySort(root.getLeft(),key);
    }

    }else if(key>value){
    if(root.getRight()==null){
    Node node=new Node(key);
    root.setRight(node);
    }else{
    BinarySort(root.getRight(),key);
    }
    }
    }

    /**
    * 二叉树搜索树;
    * @param root
    * @param key
    */
    public static boolean BinarySerch(Node root,int key){
    if(root==null){
    return false;
    }else if(root.getKey()==key){
    return true;
    }else if(root.getKey()>key){
    return BinarySerch(root.getLeft(),key);
    }else{
    return BinarySerch(root.getRight(),key);
    }
    }

    /**
    * 采用中序遍历法遍历一个二叉树
    * @param root
    */
    public static void inOrder(Node root){
    if(root!=null){
    inOrder(root.getLeft());
    root.visitNode();
    inOrder(root.getRight());
    }
    }

    }

  • 相关阅读:
    03.yaml语法和playbook写法
    02.ansible的常用模块
    01.ansible基本配置与使用
    24.删除表名
    23.MySQL的备份与恢复
    22.更改表名
    MySQL的表操作
    MySQL的库操作
    MySQL的用户管理
    数据库及MySQL概述
  • 原文地址:https://www.cnblogs.com/cy19/p/8186564.html
Copyright © 2011-2022 走看看