I want to get one of the leaf nodes as an output(just one of them).But not the same leaf node for everytime...I want to get a different leaf node for everytime with the help of "srand" function...I tried to solve this problem using array but could not be successfull.Then I decided to go on with a different algorithm with the help of a friend who commented on this post...
I am generating a random integer if it is odd I go on with the left child ,vice versa...
But get the same node as an output can not solve the problem...
void LeafNodesRandomly(BST*p)
{
int i;
srand(time(NULL));
i=rand()%2;//Generating a random int for determining to go right or left of a current node
//printf("%d\t",i);
while(p->left !=NULL || p->right !=NULL)
{
if(p->left==NULL && p->right!=NULL)//Just have a right child
{
p=p->right;
if(p->left==NULL && p->right==NULL)//If the right child is a leaf node print and break
{
printf("%d\t",p->data);
break;
}
}
if(p->left!=NULL && p->right==NULL)//Just have a left child
{
p=p->left;
if(p->left==NULL && p->right==NULL)//If the left child is a leaf node print and break
{
printf("%d\t",p->data);
break;
}
}
if(p->left!=NULL && p->right!=NULL)// The current node have two children
{
if(i==0)
{
p=p->left;
if(p->left==NULL && p->right==NULL)// If the randomly generated int is "0" go left child and if the left child is a leaf node print and break
{
printf("%d\t",p->data);
break;
}
}
if(i==1)
{
p=p->right;
if(p->left==NULL && p->right==NULL)// If the randomly generated int is "1" go right child and if the right child is a leaf node print and break
{
printf("%d\t",p->data);
break;
}
}
}
/*if(i==0) // If you open this if and else block you can randomly reach some of other leafs!!!
{
i=i+1;
}
else
i=i-1;
} */
}
}
This is my main function:
I have 13 or NULL as an output
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
#include "bst.h"
int main()
{
BST*root=NULL;
root=AddNode(root,9);
root=AddNode(root,11);
root=AddNode(root,7);
root=AddNode(root,13);
root=AddNode(root,10);
root=AddNode(root,5);
root=AddNode(root,6);
root=AddNode(root,8);
LeafNodesRandomly(root);
}