I am a beginner with trees and I was just trying to implement one for the first time and am generating the stackoverfloweror. I know its probably related to a bad recursion call however I dont see anything wrong with the recursion could I get a little help? The error is in this code.

How many lines are in randomdata.csv, and are the lines in any particular order?
–
xvtkAug 10 '12 at 23:26

the file is 3260953 lines and they where initially sorted and then duplicated 5 times. I was able to do what I wanted to do using and array and arraylist I want to do it with a binary tree also so I can compare the efficiency times
–
Will JamiesonAug 10 '12 at 23:45

A simple binary tree has worst case behavior for content that is already sorted. See the bible (ie; Knuth) and try balanced trees.
–
ddyerAug 10 '12 at 23:58

4 Answers
4

If the file is initially sorted, then this function looks like it will recurse N times for
a file with N lines. Java doesn't implement tail recursion, so this is sure to be a real
recursion. Rewrite it as a while loop instead of as a recursive function.

This would most likely occur if node.left == node or node.right == node or some other longer cycle in your tree.

In its current form, if the value was equal, it wouldn't trigger either if block, and would simply return (and return up the trace, as well) not adding anything. This means the cycle is probably occuring outside of this method.

You might find this bug in the only other place you're likely to create elements outside of the insert nethod: your constructor of your Tree class.

If your file is 3260953 lines long and sorted that would certainly explain your problem. If the elements are in ascending sorted order, then every time insert inserts a new element, it gets placed on the right branch of each node every time. What you end up with is a string of 3260953 linearly linked nodes which your code accesses through as many recursive calls. This will overflow the stack. Try running on a MUCH smaller file and in scrambled alphabetical order.

Red-Black Trees avoid this issue by automatically balancing the tree by redistributing the elements. Coding up such a data structure isn't so straight-forward, however.