尝试创建要在系统中用于存储字符串的二叉树。目前,该树用于添加和确认是否存在单词。删除包含2个子节点的节点时,我遇到了堆栈溢出错误。它不一致,因为它有时会起作用,有时会出错,所以我无法确定原因。
目前代码接受一个字符串,从中获取一个哈希值作为树的引用,如果计数大于一,则删除一个,否则检查以查看该节点有哪些子节点。
public void removeNode(String str)
{
int hash = str.hashCode();
if(hash==contentID)
{
if(count>1)
{
count--;
//System.out.println("Counter decreased");
return;
}
else
{
if(!hasChild())
{
if(parent.left==this)
{
parent.left=null;
//System.out.println("Object removed (No child)");
return;
}
else
{
parent.right = null;
}
}
else if(hasOneChild())
{
if(parent.left==this)
{
if(left==null)
{
parent.left = right;
//System.out.println("Object removed (One child)");
return;
}
else
{
parent.left = left;
//System.out.println("Object removed (One child)");
return;
}
}
else
{
if(left==null)
{
parent.right = right;
//System.out.println("Object removed (One child)");
return;
}
else
{
parent.right = left;
//System.out.println("Object removed (One child)");
return;
}
}
}
else
{
//This is where I believe the error is, somewhere within this else block
Node HLS = findHighestLeftValue();
//HLS Parent operations
Node HLSParent = HLS.parent;
HLSParent.right = HLS.left;
HLSParent.right.parent = HLSParent;
HLS.right = this.right;
HLS.left = this.left;
HLS.parent = this.parent;
if(this.parent == null)
{
System.out.println("Root node");
}
else if(parent.right == this)
{
parent.right = HLS;
}
else if(parent.left ==this)
{
parent.left = HLS;
}
System.out.println("Object removed (2 children)");
return;
}
}
}
else
{
if(hash>contentID)
{
try {
right.removeNode(str);
return;
}
catch(NullPointerException npe)
{
//System.out.println("Object not found to remove");
return;
}
}
else
{
try {
left.removeNode(str);
return;
}
catch(NullPointerException npe)
{
//System.out.println("Object not found to remove");
return;
}
}
}
}
Stack Trace指向的行是
try {
left.removeNode(str);
return;
}
为什么会导致堆栈溢出错误?