Update 15 August: solutions added.
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.)
sum_elements: find the sum of all the keys in the tree.
count_leaves: count all nodes in a tree that have no children.
find_min, find_max: find the smallest and largest keys, respectively, in the binary tree.
count_odd_depth: count all elements whose distance from the root ("depth") is an odd number. The root is at zero depth, its children are at depth one, etc.
Solutions for this page... (Note: I recommend you try to write these on your own, before looking at the solutions, to test your understanding.