Objectives of this lecture
The Problem
Construction
/*
Insert: insert newnode as the rightmost node of a partial tree.
Pre: newnode is a valid pointer of an entry to
be inserted into the
binary search tree.
Post:
newnode has been inserted as rightmost node of a partial binary
search tree.
Uses:
Power2.
*/
void
Insert(TreeNode *newnode, int count, TreeNode *lastnode[])
{
int level = Power2(count) + 1;
newnode->right = NULL;
newnode->left = lastnode[level-1];
lastnode[level] = newnode;
if (lastnode[level+1] &&
!lastnode[level+1]->right)
lastnode[level+1]->right = newnode;
}
#define ODD(x)
((x)/2*2 != (x))
/*
Power2: find the highest power of 2 that divides count.
Pre: x is a valid integer.
Post:
The function finds the highest power of 2 that divides x;
requires x != 0.
*/
int
Power2(int x)
{ int level;
for (level = 0; !ODD(x); level++)
x /= 2;
return level;
}
/*
ConnectSubtrees: connect free subtrees from lastnode[].
Pre: The nearly completed binary search tree has
been initialized. The
array last-node has been initialized
and contains the information
needed to complete the binary search
tree.
Post:
The binary search tree has been completed.
*/
void
ConnectSubtrees(TreeNode *lastnode[])
{ TreeNode
*p;
int
level, templevel;
for (level = MAXHEIGHT-1; level > 2
&& !lastnode[level]; level--)
; /* Find the highest node: root. */
while (level > 2) { /* Levels 1 and 2 are already
OK. */
if (lastnode[level]->right)
level--; /* Search for highest dangling node.*/
else { /* Right subtree is undefined. */
p = lastnode[level]->left;
templevel = level - 1;
do { /* Find highest entry not in left subtree. */
p = p->right;
} while (p && p ==
lastnode[--templevel]);
lastnode[level]->right = lastnode[templevel];
level = templevel;
}
}
}
/*
FindRoot: find root of tree (highest entry in lastnode).
Pre: The array lastnode contains pointers to the
occupied levels of
the binary search tree.
Post:
Return a pointer to the root of the newly created binary search
tree.
*/
TreeNode
*FindRoot(TreeNode *lastnode[])
{ int level;
for (level = MAXHEIGHT-1; level > 0
&& !lastnode[level]; level--)
;
if (level <= 0)
return NULL;
else
return lastnode[level];
}
/*
BuildTree: build nodes from GetNode into a binary tree.
Pre: The binary search tree pointed to by root
has been created.
Post:
The tree has been reorganized into a balanced tree.
Uses:
GetNode, Insert, ConnectSubtrees, FindRoot.
*/
TreeNode
*BuildTree(void)
{
TreeNode *newnode;
int count = 0; /* number of nodes so far */
int level; /* number of steps above leaves */
TreeNode *lastnode[MAXHEIGHT]; /* pointers to last node on each
level*/
for (level = 0; level < MAXHEIGHT;
level++)
lastnode[level] = NULL;
while ((newnode = GetNode()) != NULL)
Insert(newnode, ++count, lastnode);
newnode = FindRoot(lastnode);
ConnectSubtrees(lastnode);
return newnode; /* Return root of the tree. */
}
Analysis