二叉搜索树的基本java实现

package zcj;

/**
 * Created by admin on 2016/4/15.
 */
public class BinarySearchTree {
    //定义一个二叉树的节点
    private class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int element) {
            val = element;
            left = null;
            right = null;
        }
    }
    //二叉查找树元素的查找
    public boolean find(TreeNode head,int x){
        if(head==null) return false;
        if(head.val==x) return true;
        else if(head.val>x) return find(head.left,x);
        else return find(head.right,x);
    }
    //二叉查找树的元素的插入
    public TreeNode insert(TreeNode head,int x){
        if(head==null) {
            head= new TreeNode(x);
            return head;
        }
        else{
            if(head.val==x) return head ;
            else if(x<head.val){
                head.left=insert(head.left,x);
            }
            else{
                head.right=insert(head.right,x);
            }
        }
        return head;
    }
    //二叉查找树的最小元素的查找
    public TreeNode findMin(TreeNode t){
        if(t==null) return null;
        if(t.left==null) return t;
        else return findMin(t.left);
    }
    //二叉查找树元素的删除
    public TreeNode delete(TreeNode t,int x){
        if(t==null) return null;
        if(t.val>x){
            t.left=delete(t.left,x);
        }
        else if(t.val<x){
            t.right=delete(t.right,x);
        }
        else if(t.left!=null&&t.right!=null){
            TreeNode min=findMin(t.right);
            t.val=min.val;
            //删除节点min
        }
        else{
            if(t.left!=null)
                t=t.left;
            else
                t=t.right;
        }
        return t;
    }
}
其中:删除某个节点当左右子树都存在时,将右子树的最小值替换当前节点,并删除最小节点,删除代码没写
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值