node *c2(char *s){
node *tem;
if(*s == '#' || *s == '\0') tem = NULL;
else{
tem = (node*)malloc(sizeof(struct node));
tem->data = *s;
tem->left = NULL;
tem->right = NULL;
tem->left = c2(++s);
tem->right = c2(++s);
}
return tem;
}
s是一個(gè)字符數(shù)組,這樣建樹(shù)有錯(cuò)嗎?為什么輸出的結(jié)果不對(duì)呢?謝謝大家
2 回答

冉冉說(shuō)
TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個(gè)贊
tem->left = c2(++s);
tem->right = c2(++s);
構(gòu)建完左子樹(shù)后s的值只是加了1,在遞歸調(diào)用中并沒(méi)有改變當(dāng)前的s值。

肥皂起泡泡
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
tem->left = c2()
這種寫(xiě)法并沒(méi)讓樹(shù)節(jié)點(diǎn)真正鏈接起來(lái)。
改成這樣吧
typedef struct BiTNode {
char data;
struct BiTNode *left, *right;
}BiTNode, *BiTree;
void createBiTree(BiTree &T) {
char el = *s++;
if (el == '#' || el == '\0') {
T = NULL;
} else {
T = (BiTNode *)malloc(sizeof(BiTNode));
T->data = el;
createBiTree(T->left);
createBiTree(T->right);
}
}
添加回答
舉報(bào)
0/150
提交
取消