vendredi 13 mars 2015

Count the amount of balanced nodes



I'm writing an AVL tree in java, and I can't figure out how to write this simple method. I know I have to traverse each node in the tree, and check if their either a leaf or if their balance value is zero. The code below is an attempt of mine. In the output, it only counts the leaves, only when they have filled a level. It's a weird output. Psuedocode will help a lot. I'm fried so I can't figure it out by myself.



public int balanced()
{
return balanced(root);
}

private static int balanced(StringAVLNode balancedNodes)
{
int balanceCount =0 ;
int leftBalance = 0;
int rightBalance = 0;
if(balancedNodes == null)
{
balanceCount = 0;
}

if(balancedNodes.getRight() == null && balancedNodes.getLeft() == null)
{
balanceCount = 1;
}
return balanceCount;
}


It is supposed to be implemented recursively (I've never written recursively before until this class, thus maybe the confusion). It must have a driver method, hence the first method above the private static recursive one.




Aucun commentaire:

Enregistrer un commentaire