【发布时间】:2014-01-15 16:27:50
【问题描述】:
我正在为一项作业制作二叉搜索树和 AVL 树。
当我尝试将 1,000,000 个元素添加到二叉搜索树时遇到问题,但我可以将键-> 值对添加到 AVL 树。(AVLTree 没有问题)
如果我平衡二叉搜索树,与 AVL 树没有区别??(如果我平衡二叉搜索树,它变成 AVLTree 有什么意义?)
插入 15,000 个元素后,我从二叉搜索树中收到错误:
线程“main”中的异常 java.lang.StackOverflowError
项目定义:
使用这些测试和为幼稚二叉搜索树创建的代码,比较
AVL 树和朴素二叉搜索树的性能
搜索,插入和删除以及长序列上的树平衡。你应该
在树中运行多达 1000000 个元素的测试。
public class BinaryTreeExample {
public static void main(String[] args) {
new BinaryTreeExample().run();
}
static class Node
{
Node left;
Node right;
int value;
public Node(int value) {
this.value = value;
}
}
public void run() {
Node rootnode = new Node(25);
insert3(rootnode, 50_000);
for (int i = 0; i < 150_000; i++)
insert3(rootnode, i);
System.out.println("Bittaaa");
// System.out.println(getNodesCount(rootnode));
}
protected int getNodesCount(Node root) {
if (root != null) {
int counter = 1;
counter += getNodesCount(root.left);
counter += getNodesCount(root.right);
return counter;
} else
return 0;
}
void insert3(Node node, int value) {
if (value < node.value) {
if (node.left == null)
node.left = new Node(value);
else
insert3(node.left, value);
} else {
if (node.right == null)
node.right = new Node(value);
else
insert3(node.right, value);
}
}
public void printInOrder(Node node) {
if (node != null) {
printInOrder(node.left);
System.out.println(" Traversed " + node.value);
printInOrder(node.right);
}
}
}
【问题讨论】:
-
你需要在这里提供一些代码。
-
这与this question you just asked 非常相似,但更令人困惑。那里的答案和 cmets 实际上解决了这个问题的很大一部分。
-
您拥有的插入功能根本不是迭代的。 Here's an iterative insert function(它是 C#,但我很确定代码看起来相同,除了预期的名称更改,在这种情况下)。
-
好像是同一个班级作业:)
-
谢谢你这么多@Dukeling 我做到了。
标签: java algorithm tree binary-search-tree