Java二叉搜索树(Binary Search Tree)实现

本文介绍了二叉搜索树的特性,包括每个节点的左子节点值小于节点值,右子节点值大于节点值。讨论了二叉搜索树的节点类和实现类,强调在树中不允许存在重复数据。通过中序遍历可以得到升序排序结果。分析了二叉搜索树的查找、插入和删除操作的时间复杂度,指出在满树情况下,这些操作的时间复杂度为O(logN),对比链表和数组,展现了二叉搜索树在查询和插入操作上的优势。
摘要由CSDN通过智能技术生成

树集合了数组(查找速度快)和链表(插入、删除速度快)的优点

二叉树是一种特殊的树,即:树中的每个节点最多只能有两个子节点

二叉搜索树是一种特殊的二叉树,即:节点的左子节点的值都小于这个节点的值,节点的右子节点的值都大于等于这个节点的值

节点类:

public class Node {
	public int id;
	public String name;
	public Node leftChild;
	public Node rightChild;

	public Node(int id, String name) {
		this.id = id;
		this.name = name;
	}
}

实现类(如果树中允许存在重复数据,处理起来比较麻烦,故实现中不允许树中存在重复数据,即节点的右子节点的值必须大于节点的值):

搜索二叉树有一个特点,即如果使用中序遍历遍历搜索二叉树,将得到包含搜索二叉树中所有节点值的升序排序结果

public class BinarySearchTree {
	public Node root;
	
	public Node find(int key){
		if(root == null){
			System.out.println("The tree is empty!");
			return null;
		}
		Node current = root;
		while(current.id != key){
			if(key > current.id)
				current = current.rightChild;
			else
				current = current.leftChild;
			if(current == null)
				return null;
		}
		return current;
	}
	
	public boolean insert(Node node){
		if(root == null){
			root = node;
			return true;
		}
		//树中不允许插入重复的数据项
		if(this.find(node.id) != null){
			System.out.println("Node with id '" +
					node.id + "' has already existed!");
			return false;
		}
		Node current = root;
		while(current != null){
			if(node.id > current.id){
				if(current.rightChild == null){
					current.rightChild = node;
					return true;
				}
				current &#
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值