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());
    }
    }

    }

  • 相关阅读:
    [VBS]遍历XML文档
    [VBS]带参数删除扩展名不是*.h、*.c、*.cpp的全部文件
    [VBS]脚本中的字典、动态数组、队列和堆栈
    [VBS]检测计算机各硬件信息
    [cmd]如何设置 Windows 默认命令行窗口大小和缓冲区大小
    VB.NET and C# 差异
    host-only局域网络
    高并发、死锁、幂等性问题
    elasticsearch简单实现
    记一次504 Gateway Time-out
  • 原文地址:https://www.cnblogs.com/cy19/p/8186564.html
Copyright © 2011-2022 走看看