AVL tree balance factor

hi there,

At University we need to add an algorithm to calculate the balance factor of each node in an AVL treewithout using the hight to calculate it.

All we are alloud to use is the int bal attribute and the matchingint getBalance() andchageBalance(int bal) Methods supplied in the node class.

My attempt sometimes works and mostly doesn't. Heres what i wrote to the end of theNode insertNode(char key, Node partTree) Method:

if(partTree.getNodeLeft()==null && partTree.getNodeRight()==null)

{

System.out.print("Case 1 (0,0) | ");

partTree.bal=0;

}

elseif(partTree.getNodeLeft()!=null && partTree.getNodeRight()==null)

{

System.out.print("Case 2 (1,0) | ");

partTree.changeBalance(-1);

}

elseif(partTree.getNodeLeft()==null && partTree.getNodeRight()!=null)

{

System.out.print("Case 3 (0,1) | ");

partTree.changeBalance(+1);

}

else

{

System.out.print("Case 4 (1,1) | ");

partTree.bal = partTree.getNodeRight().getBalance() + partTree.getNodeLeft().getBalance();

}

System.out.println("["+partTree.getKey() +"] | " + partTree.getBalance());

Message was edited by:

Nark

[2046 byte] By [Narka] at [2007-10-2 19:19:05]
# 1
Think about an example:o<- What does you code produce for this node? What should it produce? \ o\o
RadcliffePikea at 2007-7-13 21:01:59 > top of Java-index,Other Topics,Algorithms...
# 2

(1)-bal=2

\

(2)-bal=1

\

(3)-bal=0

The console output is:

=====================================================

Case 1 (0,0) | [1] | 0

=====================================================

Case 1 (0,0) | [2] | 0

Case 3 (0,1) | [1] | 1

=====================================================

Case 1 (0,0) | [3] | 0

Case 3 (0,1) | [2] | 1

Case 3 (0,1) | [1] | 2

Narka at 2007-7-13 21:01:59 > top of Java-index,Other Topics,Algorithms...
# 3
Oh I see, the changeBalance method increments the variable, eh?So what exactly seems to be the problem? The more detailed the description, the more likely someone will be able to help.
RadcliffePikea at 2007-7-13 21:01:59 > top of Java-index,Other Topics,Algorithms...