Part 1 - height
As starblue says, height is just recursive. In pseudo-code:
height(node) = max(height(node.L), height(node.R)) + 1
Now height could be defined in two ways. It could be the number of nodes in the path from the root to that node, or it could be the number of links. According to the page you referenced, the most common definition is for the number of links. In which case the complete pseudo code would be:
height(node):
if node == null:
return -1
else:
return max(height(node.L), height(node.R)) + 1
If you wanted the number of nodes the code would be:
height(node):
if node == null:
return 0
else:
return max(height(node.L), height(node.R)) + 1
Either way, the rebalancing algorithm I think should work the same.
However, your tree will be much more efficient (O(ln(n))) if you store and update height information in the tree, rather than calculating it each time. (O(n))
Part 2 - balancing
When it says "If the balance factor of R is 1", it is talking about the balance factor of the right branch, when the balance factor at the top is 2. It is telling you how to choose whether to do a single rotation or a double rotation. In (python like) Pseudo-code:
if balance factor(top) = 2: // right is imbalanced
if balance factor(R) = 1: //
do a left rotation
else if balance factor(R) = -1:
do a double rotation
else: // must be -2, left is imbalanced
if balance factor(L) = 1: //
do a left rotation
else if balance factor(L) = -1:
do a double rotation
I hope this makes sense
The depth of a node is 1 more then the depth of it's deepest child.
You can do this quite simply with recursion.
unsigned int depth(node *n)
{
if (n == NULL)
return 0;
else
return MAX(depth(n->left), depth(n->right)) + 1;
}
Best Answer
Node 76 is unbalanced, for example, because its right subtree is of height 0 and the left is of height 3.