java - BST 的随机节点

标签 java binary-search-tree

我有一个方法,假设在 O(n) 时间内从 BST 获取随机节点。但是,它始终返回根节点。我的方法逻辑有什么问题?

    public Node getRandomNode(Node root) {

    // get random value between 0 to size of BST
    Random ran = new Random();
    int ranNum = ran.nextInt(size + 1);
    Node temp = root;

    return getRandomNode(ranNum, temp);
}

int count = 0;
public Node getRandomNode(int ranNum, Node temp) {

    if (temp == null)
        return null;

    count++;

    if(count <= ranNum) {
        temp.left =  getRandomNode(ranNum, temp.left);
        if(count == ranNum)
            return temp;
        temp.right =  getRandomNode(ranNum, temp.right);
    }

    return temp;

}

最佳答案

如果你看看你在做什么,你会发现无论你在做什么,你唯一返回的就是 temp。在第一次调用 getRandomNode(...) 时,您的 temp 是根节点,并且您永远不会修改 temp。因此,您将始终返回根节点。

为了解决此问题,请尝试以下操作:

if(count <= ranNum) {
    temp = getRandomNode(ranNum, temp.left);
    if(count == ranNum)
        return temp;
    temp =  getRandomNode(ranNum, temp.right);
}

return temp;

关于java - BST 的随机节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38363698/

相关文章:

c - 读取文件并跳过空格?

java - 在 GWT 中保存 Activity 状态

java - 在 JTextArea 中选择文本片段

java - 在二叉搜索树中搜索Word对象

C++ 从二叉搜索树中删除一个节点

c++ - 在 C++ 中解释类型为 'int' 的递归函数的返回值

java - 尝试获取嵌套 bean 属性时出现 NoSuchMethodException

java - 构建自助服务终端应用程序

java - 如何改变位图的大小?

c++ - 二叉搜索树 C++