In this post we will write some functions for a binary search tree.
This one needs a recursive function.
Total number of nodes in a binary tree = total number of nodes in its left subtree + 1 + total number of nodes in right subtree
And there is no recursion if node is NULL and the call must return 0.
And here is the function.
Find minimum of a binary search tree:
This function is quite simple. In a binary search tree, every node has values smaller than itself on left sub tree and values larger than itself on right subtree. So as we move to left, values get smaller and smaller.
Which means that the left extreme node is our minimum value. So if you keep traversing to left until you reach NULL, the last node is tree minimum.
int tree_minimum(NODEPTR nd)
{
while(nd->left !=NULL)
nd = nd->left;
return nd->val;
}
Count the total number of nodes in a binary search tree:
This one needs a recursive function.
Total number of nodes in a binary tree = total number of nodes in its left subtree + 1 + total number of nodes in right subtree
And there is no recursion if node is NULL and the call must return 0.
And here is the function.
int count_nodes(NODEPTR nd)
{
if(nd==NULL)
return 0;
else
return count_nodes(nd->left)+1+count_nodes(nd->right);
}
Search for a node in a BST
Let us discuss non-recursive searching of a value.
Binary search tree is an ordered tree. So when we compare search value with key of current node, if search value is greater than node value, we should branch to right. But if search value is smaller, we should branch to left. We should continue this process until value is found or a NULL is encountered.
- Start from root
- If key value of node matches search value return
- If key value of node is greater than search value, set node = node->left
- If key value of node is smaller than search value, set node = node->right
- Repeat steps 2 to 4 until match is found or node is NULL
NODEPTR search_node(NODEPTR root, int num)
{
NODEPTR temp = root;
while(temp!=NULL)
{
if(temp->val>num)
temp = temp->left;
else if(temp->val<num)
temp = temp->right;
else//we found a match
return temp;
}
return NULL;//no match
}
Finally let us look at a function to count the number of leaf nodes.
Count the number of leaf nodes
This function would be similar to count function. But here we increment count only if node has left child as NULL and right child as NULL.
int count_leaf_nodes(NODEPTR nd)
{
if(nd==NULL)
return 0;
else if(nd->left ==NULL && nd->right==NULL)
return 1;
else
return count_leaf_nodes(nd->left)+count_leaf_nodes(nd->right);
}
Comments
Post a Comment