CITS2002 Systems Programming  
prev
CITS2002 CITS2002 schedule  

Storing and searching ordered data - a binary tree, continued

Knowing that we've built the binary tree to maintain an order of its elements, we exploit this property to find elements:


bool find_recursively(BINTREE *t, int wanted)
{
    if(t != NULL) {
        int order = (t->value - wanted);

        if(order == 0) {
            return true;
	}
        else if(order > 0) {
            return find_recursively(t->left, wanted);
	}
        else {
            return find_recursively(t->right, wanted);
	}
    }
    return false;
}


bool find_iteratively(BINTREE *t, int wanted)
{
    while(t != NULL) {
        int order = (t->value - wanted);

        if(order == 0) {
            return true;
	}
        else if(order > 0) {
            t = t->left;
	}
        else {
            t = t->right;
	}
    }
    return false;
}

Of note:
  • we search for a value in the tree with:
    bool found = find_recursively(tree_root, wanted_value);
  • we do not modify the tree when searching, we simply 'walk' over its elements, determining whether to go-left or go-right depending on the relative value of each element's data to the wanted value.
  • some (more complicated) variants of the binary-tree re-balance the tree by moving recently found values (their nodes) closer to the root of the tree in the hope that they'll be required again, soon.
  • if the required value if found, the searching functions return true; otherwise we keep walking the tree until we find the value or until we can no longer walk in the required direction (because either the left or the right pointer is NULL).

 


CITS2002 Systems Programming, Lecture 19, p19, 3rd October 2023.