StackOverflowError with a binary tree
Have the following insertion method for a left child - right sibling tree - seems to be causing a StackOverflowError
at the line that called addpage
again within the private version of the method. Can anyone help advise how it can be fixed? Sorry if this has been asked before.
public PageNode addPage(String PageName)
{
PageNode ParentNode=new PageNode();
ParentNode.page=currentPage.page;
if (this.homePage==null)
this.homePage=ParentNode.parent;
else
ParentNode=this.addPage(PageName,ParentNode.parent);
return ParentNode;
}
private PageNode addPage(String PageName, PageNode ParentNode)
{
ParentNode = new PageNode();
ParentNode.page=new Page(PageName);
if (this.currentPage.page.compareTo(开发者_StackOverflowParentNode.page)==0)
{
System.out.println("attempt to insert a duplicate");
}
else
if (ParentNode.page.compareTo(currentPage.page)<0)
if(currentPage.firstchild == null)
currentPage.firstchild=ParentNode;
else
ParentNode = addPage(PageName, ParentNode.firstchild);
else if(currentPage.nextsibling == null)
currentPage.nextsibling=ParentNode;
else
ParentNode = addPage(PageName, ParentNode.nextsibling);
return ParentNode;
}
rewrite the methods to iterate instead of recurse.
Java doesn't implement tail recursion removal.
You are trying to implement a binary search tree. You should guarantee that insert/delete/lookup operations take O(logn)
time in your search tree. Your addPage
method doesn't rebalance the tree so in the worst case, the height of your tree is O(n)
. See Big-O notation if you are unfamiliar with the notation. Learn about Red-Black/AVL trees.
You are using recursion to add new nodes. As the height of the tree can get as big as O(n)
, you exceed the limit on stack size.
I don't know the default upper bound on stack size per thread in JVM.
精彩评论