CmSc 250 Intro to Algorithms
Trees

A. Java version
Class TreeNode
{
Object element;
TreeNode firstChild;
TreeNode nextSibling;
}
B. C++ version
struct Treenode
{
Object element;
Treenode *firstChild;
Treenode *nextSibling;
};

Each node has at most two children.
Height of a well-balanced tree with N leaf-nodes : about log2N.

4. 1. Computing the height of a binary tree
Consider the following binary tree

At each level the number of the nodes is doubled.
There are three levels, and the total number of nodes is:
1 + 2 + 22 + 23 = 24 - 1 = 15
Note that 24 - 1 = 2*23 - 1
Note also that 3 = log(23)
In general, if we have a tree with M levels, the number of the nodes would be:
1 + 2 + 22 + …. 2M = 2(M+1) - 1 = 2*2M - 1
Let N be the number of the nodes.
We will find now how M (the depth of the tree) depends on the number of the
nodes.
N = 2*2M - 1
2*2M = N + 1
2M = (N+1)/2
M = log((N+1)/2) = O(logN)
Thus, given a balanced binary tree with N nodes, the height of the tree is O( log(N))
Given a balanced binary tree with M levels, the number of the nodes is O(2M)
Average height of a binary tree :O(sqrt(N)) - computed by considering all possible cases of a binary tree with N nodes.
Worst case: when the tree is a list - all nodes except the leaf have only one child: height : N-1
4. 2. Binary tree traversal

Pre-order traversal:
Visit the root first then the left child then the right child
C O M P U T E R L A N D
In-order Traversal
Visit the left child then the root then the right child
P M U O C T E L R N A D
Post-order Traversal
Visit the left child then the right child then the root
P U M O L N D A R E T C
Depth first traversal = Pre-order traversal
Breadth first traversal - visit all nodes in level 0, then in level 1, etc.
Traversal is implemented by means of recursive functions.
The following is a pseudocode for traversal procedures:
pre_orderVisit(tree)
{
if (current == NULL) return;
else
{
process (current);
pre_orderVisit (left_tree);
pre_orderVisit (right_tree);
}
}
in_orderVisit(tree)
{
if (current == NULL) return;
else
{
in_orderVisit (left_tree);
process (current);
in_orderVisit (right_tree);
}
}
post_orderVisit(tree)
{
if (current == NULL) return;
else
{
post_orderVisit (left_tree);
post_orderVisit (right_tree);
process (current);
}
}
4. 3. Binary tree node declaration
A. Java version
Class BinaryNode
{
Object Element; // the data in the node
BinaryNode left; // Left child
BinaryNode right; // Right child
}
B. C++ version
struct BinaryNode
{
Object Element; // the data in the node
BinaryNode *left; // Left child
BinaryNode *right; // Right child
};
4. 4. Expression trees
Learning goals
Exam-like questions and problems