gpt4 book ai didi

java - 在数组列表中存储二叉搜索树

转载 作者:太空宇宙 更新时间:2023-11-04 13:07:40 24 4
gpt4 key购买 nike

我正在尝试采用具有 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com