登录
首页 >  文章 >  java教程

Java 中从头开始的二叉搜索树

来源:dev.to

时间:2024-07-12 09:19:02 483浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习文章的朋友们,也希望在阅读本文《Java 中从头开始的二叉搜索树》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新文章相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

Java 中从头开始的二叉搜索树

简介
二叉搜索树 (bst) 是一种二叉树,其中每个节点最多有两个子节点,称为左子节点和右子节点。对于每个节点,左子树仅包含值小于该节点值的节点,右子树仅包含值大于该节点值的节点。 bst 用于高效的搜索、插入和删除操作。

为什么使用二叉搜索树?
bst 有几个优点:

高效搜索:搜索、插入、删除平均时间复杂度为o(log n)。
动态项目集:支持动态操作,与静态数组不同。
有序元素:bst 的中序遍历会产生按排序顺序排列的元素。
构建 bst 的分步指南
步骤一:定义节点结构
第一步是定义树中节点的结构。每个节点将具有三个属性:一个值、对左子节点的引用和对右子节点的引用。

public class treenode {
    int value;
    treenode left;
    treenode right;

    treenode(int value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

第2步:使用构造函数创建bst类
接下来,我们创建 bst 类,其中包含对树根的引用以及插入元素的方法。

public class binarysearchtree {
    treenode root;

    public binarysearchtree() {
        this.root = null;
    }
}

第三步:实现插入方法
要将元素插入 bst,我们需要找到新节点的正确位置。插入方法通常实现为递归函数。

public void insert(int value) {
    root = insertrec(root, value);
}

private treenode insertrec(treenode root, int value) {
    // base case: if the tree is empty, return a new node
    if (root == null) {
        root = new treenode(value);
        return root;
    }

    // otherwise, recur down the tree
    if (value < root.value) {
        root.left = insertrec(root.left, value);
    } else if (value > root.value) {
        root.right = insertrec(root.right, value);
    }

    // return the (unchanged) node pointer
    return root;
}

可视化
为了更好地理解插入是如何工作的,让我们考虑一个例子。假设我们要在 bst 中插入以下数字序列:50, 30, 70, 20, 40, 60, 80。

50
  50
 /
30
  50
 /  \
30  70
50
 /  \
30  70
/

插入40:

  50
 /  \
30  70
/ \

插入60

  50
 /  \
30  70
/ \  /

插入80:

  50
 /  \
30  70
/ \  / \

完整代码
这是创建 bst 和插入元素的完整代码:

public class BinarySearchTree {
    TreeNode root;

    public BinarySearchTree() {
        this.root = null;
    }

    public void insert(int value) {
        root = insertRec(root, value);
    }

    private TreeNode insertRec(TreeNode root, int value) {
        if (root == null) {
            root = new TreeNode(value);
            return root;
        }

        if (value < root.value) {
            root.left = insertRec(root.left, value);
        } else if (value > root.value) {
            root.right = insertRec(root.right, value);
        }

        return root;
    }

    // Additional methods for traversal, search, and delete can be added here

    public static void main(String[] args) {
        BinarySearchTree bst = new BinarySearchTree();
        int[] values = {50, 30, 70, 20, 40, 60, 80};
        for (int value : values) {
            bst.insert(value);
        }

        // Add code to print or traverse the tree
    }
}

class TreeNode {
    int value;
    TreeNode left;
    TreeNode right;

    TreeNode(int value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

以上就是《Java 中从头开始的二叉搜索树》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>