且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建一个二进制搜索树,其中包括从1到n的所有数字

更新时间:2021-11-25 22:54:23

根节点上的数据将为(n + 1)/ 2 ;如果您有一个表示范围 [i..j] 的子树,则该子树的根为(i + j)/ 2 (使用整数算法)。

The data on the root node would be (n+1)/2; if you've got a subtree representing the range [i..j], the root of that subtree is (i+j)/2 (using integer arithmetic).

您可以使用以下事实递归构建树:

You can build the tree recursively using that fact:

static BinaryNode build(int i, int j) {
    if (i > j) return null;

    int mid = (i + j) / 2;  // Assumes i >= 0.

    BinaryNode node = new BinaryNode();
    node.data = mid;

    node.left = build(i, mid - 1);
    if (node.left != null) node.left.parent = node;

    node.right = build(mid + 1, j);
    if (node.right != null) node.right.parent = node;

    return node;
}

然后启动递归调用:

BinaryNode node = build(1, n);

但是必须指出的是,这样的二叉搜索树(将连续的整数从1存储到n)是没有用的:您也可以简单地使用数组,然后使用数组索引搜索它。

It must be pointed out, however, that such a binary search tree (storing contiguous integers from 1 to n) is useless: you may as well simply use an array, and "search" it using an array index.