icp/oer/courses/c-advanced/sections/01-introduction/06-tree/content.md

1.6 KiB

Now that we covered the basic linear data-structures, let's move on to once, which branch out. This task is about trees. A tree consists of connected nodes and each node has a certain amount of children nodes. The nodes, which don't have any children are called leaves and the start node is called a root. A tree also doesn't have any circles, meaning that no path from one node should lead back to it's self. Trees are often associated with sorting, hierarchical data or decisions.

This description is for trees in general. The one we will discuss is called a binary-search-tree. The only difference to the normal tree is, that it only has two children and all the left children have a lower search value than the node and all the right nodes have a higher one. These kind of trees are very useful for efficient searching.

For this tree we want to be able to perform four operations. - We want to be able to automatically insert an element into the right place. - We want to delete an element without destroying the definition of the binary-search-tree - We want to find an element in the tree - And we want to print out all the elements in a sorted way

Recursion is a good strategy to write functions for trees.

All but the delete functions are straight forward. The delete function needs some special casing. If there are both children present, you have to find the lowest value on the right and replace the current one with it and then recursivly delete that one. If there are less than two children, the deletion is trivial.

Your task is to implement all these functions.