3.2.1 Construction

Listing 4 is the C code to add a value (node) to a binary search tree.


Listing 4:addtobstree
 
1void BSTree_add(struct Tree *pTree, int value) 
2{ 
3  if (Tree_isempty(pTree)) 
4  { 
5    Tree_setrootvalue(pTree, value); 
6  } 
7  else 
8  { 
9    if (value <= Tree_getrootvalue(pTree) 
10    { 
11      BSTree_add(Tree_getlefttree(pTree), value); 
12    } 
13    else 
14    { 
15      BSTree_add(Tree_getrighttree(pTree), value); 
16    } 
17  } 
18}

If you prefer a version with fewer lines, you can use the one in listing 5. However, be warned that this shorter version is structurally weak, and the indentation does not reflect the structure of the actual code!


Listing 5:addtobstree
 
1void BSTree_add(struct Tree *pTree, int value) 
2{ 
3  if (Tree_isempty(pTree)) Tree_setrootvalue(pTree, value); 
4  else if (value <= Tree_getrootvalue(pTree) 
5    BSTree_add(Tree_getlefttree(pTree), value); 
6  else 
7    BSTree_add(Tree_getrighttree(pTree), value); 
8}