我想做我的功課,但我有一些困難。二叉樹 - 打印葉到葉的路徑[C]
創建一個遞歸函數,用於在整數二叉樹(即樹保留整數)中打印葉與另一葉之間的路徑。
int printPath(Tree * t,int a,int b)。
注意:您將不得不處理以下情況:
有樹沒有一個和/或b。如果是這樣,則返回-1。
如果存在,則打印值爲
a
的節點與其值爲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。
你用什麼概念來解決它?簡單的算法(解釋)? – Dineshkumar