我正在尝试采用具有 n 个元素的二叉搜索树并将它们存储在数组列表中。目前,它们在 arraylist 中的存储位置基于树的根为元素 1(p = 其父元素在数组中的索引)左子元素将位于索引 p*2,右子元素将位于索引 p*2+1。
目前我尝试使用以下代码执行此操作:
public static void arraywriter(TreeNode<String> node) throws FileNotFoundException
{
int pos = 1;
outputform.set(pos, node.getElement());
pos = pos*2;
if(node.getLeft() != null) {
arraywriter(node.getLeft());
}
pos = pos+1;
if(node.getRight() != null) {
arraywriter(node.getRight());
}
}
我的逻辑有什么问题吗?我该如何做这个工作? 目前,如果我使用它,然后尝试打印出输出形式的内容(这是数组列表的名称,它的基本大小为 10,000),我得到:索引一返回为 null,其余为“n”,这也是我初始化每个元素的内容。
谢谢!
最佳答案
您始终使用 pos 的固定值 1,这意味着您一次又一次地覆盖它。
考虑使用类似的东西:
public static void arraywriter(TreeNode<String> node, int pos) throws FileNotFoundException
{
outputform.set(pos, node.getElement());
pos = pos*2;
if(node.getLeft() != null) {
arraywriter(node.getLeft(), pos);
}
pos = pos+1;
if(node.getRight() != null) {
arraywriter(node.getRight(), pos);
}
}
关于java - 在数组列表中存储二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34276634/