二叉搜索树的实现过程(增、删)

原文链接: https://www.cnblogs.com/yahuian/p/10813614.html
二叉搜索树的增删查


BinarySearchTree.java

package Tree;

public class BinarySearchTree {
    //定义节点
     class Node {
        int data;//数据域
        Node left;//左子树
        Node right;//右子树
        public Node() {
        }
    }

    //定义根节点
    private Node root;
    public Node getRoot() {
        return root;
    }

    /**
     * 创建这颗二叉搜索树
     *
     * @param key
     */
    public void insert(int key) {
        Node node = new Node();
        node.data = key;
        if (root == null) {
            //1.第一次插入节点
            root = node;
            return;
        }
        //2.正常插入节点的情形:拿着key的值,向下搜索二叉树,将它插入到某节点下方
        Node current = root; //从根节点开始找插入点
        Node pre; //当前指针移动时,记录其父节点位置
        while (true) {
            pre = current; //定义一个父指针,始终指向当前指针,防止当前指针后移后找不到插入位置。
            if (key < current.data) {
                current = current.left;
                if (current == null) {
                    pre.left = node;
                    return;
                }
            } else {
                current = current.right;
                if (current == null) {
                    pre.right = node;
                    return;
                }
            }
        }
    } //插入成功

    /**
     * 中序打印这颗二叉搜索树
     */
    public void midPrint(Node root) {
        if (root != null) {
            midPrint(root.left);
            System.out.println(root.data);
            midPrint(root.right);
        }
    }

    /**
     * 查找二叉树中的某节点
     */
    public Node find(int key){
        //从根节点开始搜索
        Node current = root;
        while(current != null){
            if (current.data == key){
                return current;
            }else if (key < current.data){
                current = current.left;
            }else if (key > current.data){
                current = current.right;
            }
        }
        //如果没找到,此时的current已经移到了叶子节点的null
        return current;
    }

    /**
     * 打印节点
     * @param node
     */
    public void show(Node node)
    {    //输出节点的数据域
        if(node!=null)
            System.out.println(node.data);
        else
            System.out.println("null");
    }


}


Test.java

public class Test {
    public static void main(String[] args) {
        BinarySearchTree bst = new BinarySearchTree();
        bst.insert(1);
        bst.insert(5);
        bst.insert(9);
        bst.insert(3);
        bst.midPrint(bst.getRoot());

        bst.show(bst.find(10));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值