如何随机地向二叉搜索树中插入节点?

huangapple go评论67阅读模式
英文:

How do I randomly insert nodes into a binary search tree?

问题

public void Insert(Comparable key, Object data)
{
    // Create node
    Node node = new Node(key, data);

    // Walk down the tree 
    Node parent = null;
    Node child = root;
    while (child != null)
    {
        // Parent goes down
        parent = child;

        // Child goes down
        if (key.compareTo(child.GetKey()) == 0)
            throw new RuntimeException("Duplicate key.");
        else if (key.compareTo(child.GetKey()) < 0)
            child = child.left;
        else
            child = child.right;        
    }

    // Hang new node from parent or make it the root
    node.parent = parent;
    if (parent == null)
        root = node;
    else if (key.compareTo(parent.GetKey()) < 0)
        parent.left = node;
    else
        parent.right = node;
}


class Test
{
    public static void main(String args[])
    {
        Tree tree = new Tree();
    
        // Create keys
        Node n1 = new Node(null, "1");
        Node n2 = new Node(null, "2");
        Node n3 = new Node(null, "3");
        Node n4 = new Node(null, "4");
        Node n5 = new Node(null, "5");
        Node n6 = new Node(null, "6");
        Node n7 = new Node(null, "7");
        
        // Create Scanner
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter 'sorted' or 'random': ");
        String s = scanner.nextLine();

        if (s.equals("sorted"))
        {
            tree.Insert("1", n1.GetData());
            tree.Insert("2", n2.GetData());
            tree.Insert("3", n3.GetData());
            tree.Insert("4", n4.GetData());
            tree.Insert("5", n5.GetData());
            tree.Insert("6", n6.GetData());
            tree.Insert("7", n7.GetData());
        }

        if (s.equals("random"))
        {
            tree.Insert("5", n5.GetData());
            tree.Insert("2", n2.GetData());
            tree.Insert("1", n1.GetData());
            tree.Insert("3", n3.GetData());
            tree.Insert("6", n6.GetData());
            tree.Insert("7", n7.GetData());
            tree.Insert("4", n4.GetData());
        }

        if (!s.equals("random") && !s.equals("sorted"))
            throw new RuntimeException("Invalid input.");
    }
}
英文:

I'm a student learning about data structures in Java. I'm less than a beginner so please don't criticize my code too hardly :).

I want to randomly insert nodes into a binary search tree, but don't know how to do this if not manually.

I'll paste the Insert() method here and how I was previously inserting. Also I'm getting a compilation error because of the scanner. Any idea why?

	{
// Create node
Node node = new Node(key, data);
// Walk down the tree 
Node parent = null;
Node child = root;
while (child != null)
{
// Parent goes down
parent = child;
// Child goes down
if (key.compareTo(child.GetKey()) == 0)
throw new RuntimeException(&quot;Duplicate key.&quot;);
else if (key.compareTo(child.GetKey()) &lt; 0)
child = child.left;
else
child = child.right;		
}
// Hang new node from parent or make it the root
node.parent = parent;
if (parent == null)
root = node;
else if (key.compareTo(parent.GetKey()) &lt; 0)
parent.left = node;
else
parent.right = node;
}
import java.util.Scanner;
class Test
{
public static void main(String args[])
{
Tree tree = new Tree();
// Create keys
Node n1 = new Node(null, &quot;1&quot;);
Node n2 = new Node(null, &quot;2&quot;);
Node n3 = new Node(null, &quot;3&quot;);
Node n4 = new Node(null, &quot;4&quot;);
Node n5 = new Node(null, &quot;5&quot;);
Node n6 = new Node(null, &quot;6&quot;);
Node n7 = new Node(null, &quot;7&quot;);
// Create Scanner
Scanner scanner = new Scanner();
System.out.print(&quot;Enter &#39;sorted&#39; or &#39;random&#39;: &quot;);
String s = scanner.nextLine();
if (s == &quot;sorted&quot;)
tree.Insert(&quot;1&quot;, n1.GetData());
tree.Insert(&quot;2&quot;, n2.GetData());
tree.Insert(&quot;3&quot;, n3.GetData());
tree.Insert(&quot;4&quot;, n4.GetData());
tree.Insert(&quot;5&quot;, n5.GetData());
tree.Insert(&quot;6&quot;, n6.GetData());
tree.Insert(&quot;7&quot;, n7.GetData());
if (s == &quot;random&quot;)
tree.Insert(&quot;5&quot;, n5.GetData());
tree.Insert(&quot;2&quot;, n2.GetData());
tree.Insert(&quot;1&quot;, n1.GetData());
tree.Insert(&quot;3&quot;, n3.GetData());
tree.Insert(&quot;6&quot;, n6.GetData());
tree.Insert(&quot;7&quot;, n7.GetData());
tree.Insert(&quot;4&quot;, n4.GetData());
if (s != &quot;random&quot; &amp;&amp; s != &quot;sorted&quot;)
throw new RuntimeException(&quot;Invalid input.&quot;);
}
}
</details>
# 答案1
**得分**: 0
以下是翻译好的内容:
在`Collections`类中有一个标准库方法可以对列表进行随机排序。要使用它,我们必须创建一个包含数据的列表,然后调用`Collections.shuffle`方法:
```java
List<String> data = new ArrayList();
for (int i = 1; i <= 7; i++) {
data.add(String.valueOf(i));
}
Collections.shuffle(data);

现在您可以将数据插入到树中:

for (String item: data) {
    tree.Insert(item, item);
}

关于编译错误,没有一个不带参数的Scanner构造函数。您可能想要传入系统的标准输入流。

// 创建Scanner
Scanner scanner = new Scanner(System.in);

我还注意到另一件事:您不能使用==来比较字符串,比如if (s == "sorted"),您必须使用equals方法:if (s.equals("sorted"))

还有一件事,您需要在if语句中使用大括号{ }。否则,您希望有条件地运行的内容将始终运行。

if (s.equals("sorted")) {
    tree.Insert("1", n1.GetData());
    tree.Insert("2", n2.GetData()); // <-- 无论s是什么都会运行
}
英文:

There is a standard library method in the Collections class to shuffle a list. To use it, we must create a List with the data, and then call Collections.shuffle:

List&lt;String&gt; data = new ArrayList();
for (int i = 1; i &lt;= 7; i++) {
data.add(String.valueOf(i));
}
Collections.shuffle(data);

Now you can just insert the data into the tree:

for (String item: data) {
tree.Insert(item, item);
}

Regarding the compilation error, there is no Scanner constructor that takes no arguments. You probably wanted to pass in the system standard input stream.

    // Create Scanner
Scanner scanner = new Scanner(System.in);

Another thing I noticed: you can't compare strings with == like in if (s == &quot;sorted&quot;) you must use the equals method instead: if (s.equals(&quot;sorted&quot;))

Yet another thing, you need to use brackets { } with if-statements. Otherwise things that you meant to run conditionally will run always.

    if (s == &quot;sorted&quot;)
tree.Insert(&quot;1&quot;, n1.GetData());
tree.Insert(&quot;2&quot;, n2.GetData()); // &lt;-- runs no matter what s is

huangapple
  • 本文由 发表于 2020年4月9日 04:12:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/61109231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定