二叉搜索树

import java.io.*;
/**
从数组array=[7 4 1 5 13 8 11 12 15 9 2]搜索数字
首先创建二叉搜索树(比根节点小的数放在左子节点,比根节点大的数放在右子节点),
返回搜索次数
*/

//节点类
class Node{
  Node leftChild;
  Node rightChild;
  int value;
  public Node(int value){
    this.value = value;
    this.leftChild = null;
    this.rightChild = null;
  }
}

//构造二叉搜索树
class BinaryTree{
  public Node rootNode;
  private int count = 1;
  public void addBinaryTree(int value){
    //根节点
    if(rootNode == null){
      rootNode = new Node(value);
      return;
    }
    Node currentNode = rootNode;
    while(true){
      if(value < currentNode.value){//左节点
        if(currentNode.leftChild == null){
          currentNode.leftChild = new Node(value);
          return;
        }else{
          currentNode = currentNode.leftChild;
        }
      }else{//右节点
        if(currentNode.rightChild == null){
          currentNode.rightChild = new Node(value);
          return;
        }else{
          currentNode = currentNode.rightChild;
        }
      }
    }
  }
  
  public boolean findNode(Node node, int value){
    if(node == null){
      return false;
    }else if(value == node.value){
      System.out.println("共搜索"+ count + "次");
      return true;
    }else if(value < node.value){
      count+=1;
      return findNode(node.leftChild, value);
    }else{
      count+=1;
      return findNode(node.rightChild, value);
    }
  }
}

public class BinarySearch{
  public static void main(String[] args) throws IOException{
    try{
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      int[] array = {7, 4, 1, 5, 13, 8, 11, 12, 15, 9, 2};
      System.out.print("请输入搜索值:");
      int value = Integer.parseInt(br.readLine());
      BinaryTree bt = new BinaryTree();
      for(int i = 0; i < array.length; ++i){
        bt.addBinaryTree(array[i]);
      }
      bt.findNode(bt.rootNode, value);
    }catch(IOException e){
      e.printStackTrace();
    }
  }
}


二分树:每一个节点的数据大于左子节点且小于右子节点。

二分树便于排序和搜索,二叉排序树和二叉搜索树都是二分树的一种。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值