【发布时间】:2020-04-08 20:12:17
【问题描述】:
我是一名学习 Java 数据结构的学生。我还不是初学者,所以请不要太严厉地批评我的代码:)。
我想将节点随机插入到二叉搜索树中,但如果不是手动的话,我不知道该怎么做。
我将在此处粘贴 Insert() 方法以及我之前的插入方式。由于扫描仪,我也遇到了编译错误。知道为什么吗?
{
// 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;
}
import java.util.Scanner;
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.out.print("Enter 'sorted' or 'random': ");
String s = scanner.nextLine();
if (s == "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 == "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 != "random" && s != "sorted")
throw new RuntimeException("Invalid input.");
}
}
【问题讨论】:
-
“随机插入”是什么意思 - 插入相同的 7 个节点但以随机顺序插入?还是使用随机数生成器生成一堆节点?
-
@Joni 是的,按随机顺序插入相同的 7 个节点
标签: java insert binary-search-tree