I'm trying to do my homework but I'm having some difficult.
Create a recursive function who prints the path between a leaf to another in an integer binary tree (i.e. the tree holds integers).
int printPath(Tree* t, int a, int b).
Note: You will have to handle the following situations:
there's no a and/or b in the tree. if so, return -1.
If there are, print all the values between the node whose value
aand the node whose valueb. return 0.
I tried this code:
int print1(Tree* tree, int a, int b) {
int cnt;
int c = MAX(a, b), d = MIN(a, b);
a = d;
b = c;
if (!tree)
return -1;
/*
if (tree->key.id > b || tree->key.id < a) {
if(tree->key.id > b)
cnt = print(tree->left, a, b);
else
cnt = print(tree->right, a, b);
}*/
if (tree->key.id == a || tree->key.id == b) {
if (tree->key.HWGrade) {
printf("e) , %d -> ", tree->key.id);
tree->key.HWGrade = 0;
}
return 0;
}
if (tree->key.id > b) {
cnt = print1(tree->left, a, b);
if (tree->key.HWGrade) {
printf("c) , %d -> ", tree->key.id);
tree->key.HWGrade = 0;
} else
return 0;
} else {
if (tree->key.id > a) {
cnt = print1(tree->left, a, b);
if (tree->key.id != a && tree->key.id != b && !cnt) {
if (tree->key.HWGrade) {
printf("d) , %d -> ", tree->key.id);
tree->key.HWGrade = 0;
} else
return 0;
}
}
}
if (tree->key.id < a) {
cnt = print1(tree->right, a, b);
if (tree->key.id != a && tree->key.id != b && !cnt) {
if (tree->key.HWGrade) {
printf("a) , %d -> ", tree->key.id);
tree->key.HWGrade = 0;
} else
return 0;
}
} else {
if (tree->key.id < b) {
cnt = print1(tree->right, a, b);
if (tree->key.id != a && tree->key.id != b && !cnt) {
if (tree->key.HWGrade) {
printf("b) , %d -> ", tree->key.id);
tree->key.HWGrade = 0;
} else
return 0;
}
}
}
if (cnt == 0)
return 0;
return -1;
}
But it doesn't seem to work.
Structure who's been used:
typedef struct {
int id;
int HWGrade;
int ExamGrade;
} MatamStudent;
typedef struct Tree{
int Data;
struct Link* list;
MatamStudent key;
struct Tree *left;
struct Tree *right;
} Tree;
I'm using GCC with Eclipse under Ubuntu.