【问题标题】:How to create a binary search tree that includes all numbers from 1 to n如何创建一个包含从 1 到 n 的所有数字的二叉搜索树
【发布时间】:2017-03-05 23:08:09
【问题描述】:

我正在尝试创建一个包含从 1 到 n 的所有数字的二叉搜索树。一个例子是从 1 到 5 就像

根:3

root.left: 2

root.left.left = 1

root.right = 4

root.right.right = 5

这棵树恰好不是很平衡,但我更喜欢一种尽可能平衡树的方法。

我正在尝试为此创建自己的数据结构,所以我基本上只是写了一个 Node 类:

    private class BinaryNode{
        int data;
        BinaryNode left;
        BinaryNode right;
        BinaryNode parent;
    }

我计划将它放在另一个类中,它代表树本身。我一直在寻找一种确定左/右值以适当地构建树的好方法,不胜感激!

【问题讨论】:

  • 您需要在 BinaryNode 类中使用 balanceFactor 变量,以便您可以在进行过程中平衡树。无论如何,如果您想在进行过程中平衡树,为什么不尝试实现 AVL 树而不是二叉搜索树?
  • 我正在考虑使用 AVL,但我想我会先试试这个
  • 哦,好吧,我明白了。

标签: java algorithm tree binary-search-tree


【解决方案1】:

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

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

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 的连续整数)是没有用的:你也可以简单地使用一个数组,然后使用数组索引“搜索”它。

【讨论】:

  • 如果不是太复杂,你能展示如何从一个有序的随机数数组开始制作一个平衡的二叉树。
  • 几乎完全一样:i 和 j 成为数组索引的范围;只需将数组作为附加参数传递给build,然后使用node.data = arr[mid];。
  • 另外,你需要用build(arr, 0, arr.length-1)开始递归。
  • 这个解决方案的O(?) 复杂度是多少?
  • @GrzegorzGórkiewicz O(n)。它为范围内的每个元素精确创建 1 个节点。更正式地说,这似乎也遵循主定理:T(n) = 2*T(n/2) + const,所以T(n) \in Theta(n^(log_2 2)) = Theta(n^1) = Theta(n)。
【解决方案2】:
public void insert(int id){
    Node newNode = new Node(id);
    if(root==null){
        root = newNode;
        return;
    }
    Node current = root;
    Node parent = null;
    while(true){
        parent = current;
        if(id<current.data){                
            current = current.left;
            if(current==null){
                parent.left = newNode;
                newNode.parent = parent;
                return;
            }
        }else{
            current = current.right;
            if(current==null){
                parent.right = newNode;
                newNode.parent = parent;
                return;
            }
        }
    }
}

没有递归插入 1 到 n 个数字。

public static void main(String arg[]){
    Solution2 s = new Solution2();
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    for(int i = 1;i <= n;i++){
        s.insert(i);
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 2019-04-19
    相关资源
    最近更新 更多