二叉搜索树

89 篇文章 0 订阅
38 篇文章 1 订阅

二叉搜索树又称二叉排序树。是空树或者具有以下性质的二叉树。
1、若左子树不为空,则左子树上所有结点的值都小于根结点的值。
2、若右子树不为空,则右子树上所有结点的值都大于根结点的值。
3、它的左右子树也分别为二叉搜索树。

public class BSTree {
    public Node root = null;

    //
    public void insert(int key) {//插入
        if (root == null) {
            root = new Node(key);
            return;
        }

        Node parent = null;
        Node current = root;
        while (current != null) {
            if (key == current.key) {
                throw new RuntimeException("key 重复了: " + key);
            } else if (key < current.key) {
                parent = current;
                current = current.left;
            } else {
                parent = current;
                current = current.right;
            }
        }

        // current 就是 key 要插入的位置
        Node node = new Node(key);
        if (key < parent.key) {
            parent.left = node;
        } else {
            parent.right = node;
        }
    }

    // O(树的高度)
    public boolean find(int key) {//查找
        Node current = root;
        while (current != null) {
            if (key == current.key) {
                return true;
            } else if (key < current.key) {
                current = current.left;
            } else {
                current = current.right;
            }
        }

        return false;
    }

    private static void inorder(Node node) {//中序遍历
        if (node != null) {
            inorder(node.left);
            System.out.print(node.key + " ");
            inorder(node.right);
        }
    }

    private static void postorder(Node node) {//后序遍历
        if (node != null) {
            postorder(node.left);
            postorder(node.right);
            System.out.print(node.key + " ");
        }
    }

    public static void main(String[] args) {
        BSTree tree = new BSTree();
        tree.insert(5);
        tree.insert(3);
        tree.insert(8);
        tree.insert(2);
        tree.insert(4);
        tree.insert(7);
        tree.insert(9);
        tree.insert(1);
        tree.insert(6);

        inorder(tree.root);
        System.out.println();
        postorder(tree.root);
        System.out.println();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值