Hi all,
I have written a balanced binary search tree as part of an assignment (make a simple Spell Checker). Each node has, among other values, two height ints, leftHeight and rightHeight, to keep track of the heights of any subtrees. My problem is that after a rotation, the heights of any parent nodes and their preceding parents can be incorrect. For example, consider the following tree:
B
/ \
A C
\
D
\
E
According to my program, this tree is unbalanced because the difference between the leftHeight and rightHeight fields of node B is greater than 1 (1-3) . To fix this, a single left rotation is performed on node D, making the tree look like this:
B
/ \
A D
/ \
C E
The way my program is written, the reassignment of the heights of nodes D, C, E, is done within the rotation function, and those are correct. However, node B's rightHeight field remains the same (3), and is now incorrect (should be 2). This problem occurs each time a rotation is done, and may cause the program to attempt to rotate a node that shouldn't be rotated (in turn causing an access violation).
I have thought of adding another field to each node, parent, to facilitate readjustment of the parent's heights, but my nodes already take up more memory than I'd like, so I need another solution.
I have attached my code for the program, including a set of Inserts that illustrates the problem resulting from the height value problem.
If anyone has the time, I'd appreciate any advice on how to solve this problem. Preferably, I'd like to avoid writing another recursive function, or adding any additional fields to the AVLNode class. The best solution in this case would be to write a non-recursive function to do the height adjustment, or to add code to an existing recursive method (to increase efficiency) - I'm just not certain how to do it.
Thanks!