Binary Search Trees
Definitions, building, traversing
Definitions
struct
treeNode
{
int
data;
treeNode
*left, *right;
// struct constructor declaration
};
typedef
treeNode*
treePtr;
void insert (treePtr &temp, int id, int inv);
void mainMenu (treePtr &);
int main()
{
treePtr root;
root = NULL;
mainMenu (root);
return 0;
}
void mainMenu (treePtr &root)
{
char choice;
//code to read data from file: id number and inventory amount
//code to prompt for action - build, etc. Then calls insert if action is to build
}
void insert (treePtr &temp, int id, int inv)
{
if (NULL == temp)
temp = new treeNode (id, inv, NULL, NULL);
else
if (id < temp->id)
insert (temp->left, id, inv);
else
insert (temp->right, id, inv);
}
VLR
void preorder (treePtr temp)
{
if (temp != NULL)
{
cout << temp->data << endl;
preorder (temp->left);
preorder (temp->right);
}
}
LVR
void inorder (treePtr temp)
{
if (temp != NULL)
{
inorder (temp->left);
cout << temp->data << endl;
inorder (temp->right);
}
}
LRV
void postorder (treePtr temp)
{
if (temp != NULL)
{
postorder (temp->left);
postorder (temp->right);
cout << temp->data << endl;
}
}
private int countLeaves (TreeNode root)
{
if (root == null)
return 0;
else if ((root.getRight() == null) && (root.getLeft() == null))
return 1;
else
return countLeaves(root.getLeft()) + countLeaves (root.getRight());
}
private int height (TreeNode root)
{
if (root == null)
return 0;
else
return (max(1 + height(root.getLeft()), 1 + height(root.getRight())));
}
private int width (TreeNode root)
{
int temp;
if (root == null)
return 0;
temp = height(root.getLeft()) + 1 + height(root.getRight());
temp = max (temp, width(root.getLeft()));
return max (temp, width(root.getRight()));
}
T
private int countNodes (TreeNode root)
{
if (root == null)
return 0;
else
return countNodes(root.getLeft()) + 1 + countNodes(root.getRight());
}
public void clearTree()
{
myRoot = null;
}
private TreeNode insert (Comparable next, TreeNode root)
// pre : root points to a binary search tree
// post: next added to tree so as to preserve binary search tree
{
if (root == null)
root = new TreeNode (next, null, null);
else if(next.compareTo(root.getValue()) <= 0 )
root.setLeft(insert(next, root.getLeft()));
else
root.setRight(insert(next, root.getRight()));
return root;
}
public Object findMin()
// post: returns the minimum value in the tree (null if tree is empty)
{
if (myRoot == null)
return null;
else
return findMin(myRoot);
}
private Object findMin(TreeNode root)
// pre : root points to a nonempty binary search tree
// post: returns the minimum value stored in the tree
{
if (root.getLeft() == null)
return root.getValue();
else
return findMin(root.getLeft());
}