我正在尝试做我的家庭作业,但我遇到了一些困难。
创建一个递归函数,它打印整数二叉树中叶子到另一个叶子之间的路径(即树保存整数)。
int printPath(Tree* t, int a, int b)。
注意:您将不得不处理以下情况:
树中没有 a 和/或 b。如果是,则返回 -1。
如果有,则打印其 value
a
的节点和 value 的节点之间的所有值b
。返回 0。
我试过这段代码:
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;
}
但这似乎不起作用。
使用过的结构:
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;
我在 Ubuntu 下使用 GCC 和 Eclipse。