

Those are upper bound numbers which hold when a tree is fully expanded (i.e., a tree of depth d is complete and all nodes at depth 0 through d-1 have two children).
e.g. floor(lg31) = 4
Exercises:
class BinaryNode { // constructors BinaryNode( Comparable o ) { element = o; } BinaryNode( Comparable o, BinaryNode lt, BinaryNode rt ) { element = o; left = lt; right = rt; }// fields Comparable element; BinaryNode left; BinaryNode right; }

BinaryNode root; // start from an empty tree

A
/ \
B F
\ /
C G
/ \
D E
There are three different orders to visit nodes:
- Preorder -- 1) visit current node, 2) go left, then 3) go right
- Inorder -- 1) go left, 2) visit current node, then 3) go right
- Postorder -- 1) go left, 2) go right, then 3) visit current node
Preorder: A B C D E F G Inorder: B D C E A G F Postorder: D E C B G F A
void inorder(BinaryNode node)
{
if (node != null)
{
inorder(node.left); // go left first -- recursive call
System.out.println(node.element); // then visit (print the node data)
inorder(node.right); // and then go right -- recursive call
}
}
int SizeOfTree(BinaryNode n)
{
if (n == null)
return 0;
else
return (1 + SizeOfTree(n.left) + SizeOfTree(n.right));
}
int TreeHeight(BinaryNode n)
{
if (n == null)
return -1;
else
return (1 + Max(TreeHeight(n.left), TreeHeight(n.right)));
}
Notice the tree respects operator precedence between * and -.
NOTE: If the expression was 3 * (5 - 2), the tree above is not correct -- The correct tree is different.
Preorder: - * 3 5 2 Inorder: 3 * 5 - 2 Postorder: 3 5 * 2 -