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

本文详细介绍了如何使用Java实现二叉搜索树的插入和删除操作。内部方法findMax和findMin分别用于查找子树中的最大和最小元素。在插入操作中,根据二叉搜索树的性质进行递归插入。删除操作则考虑了节点可能有零、一或两个子节点的情况,并相应地更新子树。
摘要由CSDN通过智能技术生成

/**

  • Internal method to find the largest item in a subtree

  • @param t the node that roots the subtree

  • @return the node containing the largest item

*/

private BinaryNode findMax(BinaryNode t){

if (t == null){

return null;

}

if (t.right == null){

return t;

}

return findMax(t.right);

}

[](()1.8、insert

这个主要是根据二叉搜索树的性质,注意当树为空的情况,就可以加入新的节点了,还有当该值已经存在时,默认不进行操作;

/**

  • Internal method to insert into a subtree

  • @param x the item to insert

  • @param t the node that roots the subtree

  • @return the new root of the subtree

*/

private BinaryNode insert(AnyType x, BinaryNode t){

if (t == null){

return new BinaryNode<>(x,null,null);

}

int compareResult = myCompare(x,t.element);

if (compareResult < 0){

t.left = insert(x,t.left);

}

else if (compareResult > 0){

t.right = insert(x,t.right);

}

else{

//Duplicate; do nothing

}

return t;

}

[](()1.9、remove

imgimg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值