[   ^ to index...   |   <-- previous   |   next -->   ]

Binary search tree operations

BinaryTree::find()

The most natural definition of find() is recursive. Since we want to recurse on nodes, not on the BinaryTree wrapper class, we should define a helper function:

bool BinaryTree::find(int value) { return find_node(root, value); } bool find_node(TreeNode* node, int value) { if (node == NULL) { return false; } else if (node->key == value) { return true; } else { if (node->key > value) return find_node(node->left); else return find_node(node->right); } }

BinaryTree::size()

The most natural definition of size() is recursive as well. What does it look like?

Exercises

Can you write the following operations? (Skip the wrappers and focus on the recursive component.)


Solutions for this page... (Note: I recommend you try to write these on your own, before looking at the solutions, to test your understanding.

Last modified: Tue Aug 15 13:46:13 PDT 2000