I have to write an algorithm in C that takes in input a Binary Search Tree. The exercise defines as "left visit" the visit that starts from the root of the sub tree and go left as long as possible. Similarly it defines the "right visit". The exercise ask to print the key of the three which has the left visit strictly bigger than the right visit. It also ask to print this key in ascending order,and the algorithm must works in linear time, so I have to implement an in-order-visit-like algorithm. Now, I have written an algorithm that works in linear time but in some case it didn't work as a in-order-visit and so the printed key aren't in ascending order, but I don't know how to manage to overtake this obstacles. How can I compare the left visit and the right without first of all implement a recursion on the left and on the right?
#include<stdio.h>
#include<stdlib.h>
typedef struct _node {
int dato;
struct _node *left;
struct _node *right;
}node;
typedef struct _ret {
int sin;
int des;
}res;
node *inserisci(node *root, int insert)
{
if(root==NULL) {
node * new=(node*)malloc(sizeof(node));
new->left=NULL;
new->right=NULL;
new->dato=insert;
return new;
}
if(root->dato < insert) root->right =inserisci(root->right,insert);
else root->left = inserisci(root->left,insert);
return root;
}
res somma(node * u)
{
res ret; res ciao_sx; res ciao_dx;
if(u==NULL) return;
if(u->left==NULL && u->right==NULL)
{
ret.sin=0;
ret.des=0;
return ret;
}
if(u->left!=NULL && u->right!=NULL)
{
ciao_sx=somma(u->left);
ret.sin= ciao_sx.sin+1;
ciao_dx=somma(u->right);
ret.des= ciao_dx.des+1;
if(ret.sin > ret.des )
{
printf("%d\n",u->dato);
}
return ret;
}
if(u->left!=NULL && u->right==NULL)
{
ciao_sx=somma(u->left);
ret.sin= ciao_sx.sin+1;
ret.des= 0;
printf("%d\n",u->dato);
return ret;
}
if(u->left==NULL && u->right !=NULL)
{
ciao_dx=somma(u->right);
ret.des= ciao_dx.des +1;
ret.sin=0;
return ret;
}
}
int main()
{
int n,i,x;
scanf("%d",&n);
node *root=NULL;
for(i=0;i<n;i++) {
scanf("%d",&x);
root=inserisci(root,x);
}
somma(root);
return 0;
}