【问题标题】:How to insert random integers in a binary search tree如何在二叉搜索树中插入随机整数
【发布时间】:2016-04-29 03:16:29
【问题描述】:

对于我的作业,我正在创建一个代码,该代码从一组 10,000 个数字中生成一千个随机整数,将它们移动到一个容器中,然后移动到一个二叉搜索树中。我首先得到以下代码:

Random ran = new Random();
Integer x;{  
for(int i = 1; i <= 100; i++){
x = ran.nextInt(10,000) + 1;
}

我有一个 BSTNode 和一个 Intclass。给定 BST 类中的以下代码,我可以使用它来搜索

public boolean search(Integer value) {
    boolean retval = false;
    numofcomps ++;
    if (root == null) {
        retval = false;
    } else {
        retval = searchtree(root, value);
    }
    return retval;
}

public boolean searchtree(BSTNode<IntClass> myroot, int value) {
    numofcomps ++;
    boolean retval = false;
    if (myroot == null) {
        retval = false;
    } else {
        if (value == myroot.element.myInt) {
            retval = true;
        } else {
            if (value < myroot.element.myInt) {
                retval = searchtree(myroot.leftTree, value);
            } else {
                retval = searchtree(myroot.rightTree, value);
            }
        }
    }

我需要弄清楚如何将随机数移动到二叉树中。有什么建议吗?

【问题讨论】:

  • 您所描述的是插入操作。搜索“如何插入 BST”。
  • 你有一些search 方法,那么你的insert 方法呢?
  • 您可能想要构建一个由Nodes 组成的Tree 类,并使用和插入方法,您将在其中将Node 插入到Tree 中,其中Node 具有值随机int。插入的行为类似于搜索。所以你有了一个好的开始。

标签: java random binary-search-tree


【解决方案1】:

您可以以这种方式递归地插入元素。它假定您已经定义了这些 setter 和 getter,但您可以轻松地对其进行更改以适应您的特定接口需求。

public void insert(int val) {
    if (this.myRoot == null) {
        this.myRoot = new BSTNode<Integer>(val);
    } else {
        insert(this.myRoot, val);
    }
}

private void insert(BSTNode<Integer> node, int val) {
    if (val < node.getVal()) {
        if (node.getLeftChild() == null) {
            node.setLeftChild(new BSTNode<Integer>(val));
        } else {
            insert(node.getLeftChild(), val);
        }
    } else {
        if (node.getRightChild() == null) {
            node.setRightChild(new BSTNode<Integer>(val));
        } else {
            insert(node.getRightChild(), val);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多