3.2.2 Search

To search in a binary search tree, we can use the code in listing 6.


Listing 6:searchbstree
 
1int BSTree_find(struct Tree *pTree, int value) 
2{ 
3  int result = 0; 
4  if (!Tree_isempty(pTree)) 
5  { 
6    result = Tree_getrootvalue(pTree) == value; 
7    if (!result) 
8    { 
9      if (value <= Tree_getrootvalue(pTree)) 
10      { 
11        result = BSTree_find(Tree_getlefttree(pTree), value); 
12      } 
13      else 
14      { 
15        result = BSTree_find(Tree_getrighttree(pTree), value); 
16      } 
17    } 
18  } 
19  return result; 
20}

This code can be made more concise. The concise version is listed in listing 7.


Listing 7:searchbstree
 
1int BSTree_find(struct Tree *pTree, int value) 
2{ 
3  return Tree_isempty(pTree) ? 0 : 
4         (Tree_getrootvalue(pTree) == value) ? 1 : 
5         (value <= Tree_getrootvalue(pTree)) ? 
6           BSTree_find(Tree_getrighttree(pTree), value) : 
7           BSTree_find(Tree_getlefttree(pTree), value); 
8}