查找 ArrayList 二叉树中的 Index 是否为 null
Find if Index is null in a ArrayList binary tree
这是一个 uni 项目,我们编写了一个 "tree of life" 来提出问题,然后它会用用户的答案填充自己,作为一个二叉树,它里面有 "holes",所以基本上它可以在索引 20 上有一些数据,但在 15 上没有,所以 .size() 也不起作用
这给我带来了问题,因为我需要知道某个索引是否为空,但是如果没有找到 ArrayList.get returns IndexOutOfBoundsException(如文档所述)
if(tree.get(next) == null){
String nName = getInput();
String nCarac = getInput(nName,nome);
tree.add(next,nCarac);
tree.add(next+Math.pow(2,height), nName);
restart();
}else{
question(next,height);
}
解决这个问题的方法是什么?
它不是 "regular" 二叉树,它是这样的:
o
/ \
o o
| |
o o
/ \ / \
o oo o
看来您正试图在数组中尚不存在的位置添加一个值。无法在超出范围的索引后添加值 -
tree.add(next+Math.pow(2,height), nName);
可能是越界了。
我认为你应该考虑另一种数据结构。就像你说的:一棵树。不是让树成为一个 ArrayList<>,你应该有一个
class TreeNode{
ArrayList children = new ArrayList<TreeNode>();
...Some other properties like "nName" and nome ...
}
创建树,您可以拥有一个根节点并连续添加子节点 - 例如:
TreeNode root = new TreeNode();
TreeNode childLevel1 = new TreeNode();
root.children.add(childLevel1);
TreeNode childLevel2 = new TreeNode();
childLevel1.children.add(childLevel2);
它给出了一棵两层深的树,每层有一个节点。
root
|
childLevel1
|
childLevel2
- 但也许我误解了这个问题?
这是一个 uni 项目,我们编写了一个 "tree of life" 来提出问题,然后它会用用户的答案填充自己,作为一个二叉树,它里面有 "holes",所以基本上它可以在索引 20 上有一些数据,但在 15 上没有,所以 .size() 也不起作用
这给我带来了问题,因为我需要知道某个索引是否为空,但是如果没有找到 ArrayList.get returns IndexOutOfBoundsException(如文档所述)
if(tree.get(next) == null){
String nName = getInput();
String nCarac = getInput(nName,nome);
tree.add(next,nCarac);
tree.add(next+Math.pow(2,height), nName);
restart();
}else{
question(next,height);
}
解决这个问题的方法是什么?
它不是 "regular" 二叉树,它是这样的:
o
/ \
o o
| |
o o
/ \ / \
o oo o
看来您正试图在数组中尚不存在的位置添加一个值。无法在超出范围的索引后添加值 -
tree.add(next+Math.pow(2,height), nName);
可能是越界了。
我认为你应该考虑另一种数据结构。就像你说的:一棵树。不是让树成为一个 ArrayList<>,你应该有一个
class TreeNode{
ArrayList children = new ArrayList<TreeNode>();
...Some other properties like "nName" and nome ...
}
创建树,您可以拥有一个根节点并连续添加子节点 - 例如:
TreeNode root = new TreeNode();
TreeNode childLevel1 = new TreeNode();
root.children.add(childLevel1);
TreeNode childLevel2 = new TreeNode();
childLevel1.children.add(childLevel2);
它给出了一棵两层深的树,每层有一个节点。
root
|
childLevel1
|
childLevel2
- 但也许我误解了这个问题?