問題代碼分析
int CreateBiTree(BiTree *t) {
int ch;
scanf("%d", &ch);
if (ch == ' ') t = NULL; // 錯誤:比較 int 與字符常量
else {
t = (BiTree*)malloc(sizeof(BiTree));
t->data = ch;
CreateBiTree(t->lchild); // 錯誤:傳值調用,無法修改實參指針
CreateBiTree(t->rchild);
}
return 0;
}
三大核心錯誤
- 終止條件錯誤:
ch == ' ' 永遠為假(ASCII 32),導致無限遞歸等待輸入。應用具體數值如 0 或 -1 表示空節點。
- 指針傳值而非傳址:函數參數
BiTree *t 是指針副本,內部 t = malloc(...) 不會影響調用者的指針。必須傳 BiTree **t 或返回新節點指針。
- 未處理輸入緩沖:連續
scanf 可能遺留換行符,建議檢查返回值。
修正版代碼
#include <stdio.h>
#include <stdlib.h>
typedef struct BiTree {
int data;
struct BiTree *lchild, *rchild;
} BiTree;
// 返回新建節點指針,0 表示空節點
BiTree* CreateBiTree() {
int ch;
if (scanf("%d", &ch) != 1) return NULL;
if (ch == 0) return NULL; // 以 0 為結束標記
BiTree *node = (BiTree*)malloc(sizeof(BiTree));
node->data = ch;
node->lchild = CreateBiTree();
node->rchild = CreateBiTree();
return node;
}
void PreOrder(BiTree *root) {
if (root) {
printf("%d ", root->data);
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
int main() {
printf("請按先序輸入節點值,0 表示空:\n");
BiTree *root = CreateBiTree();
printf("先序遍歷結果:");
PreOrder(root);
return 0;
}
調試建議
- 輸入示例:
1 2 0 0 3 0 0 代表根 1,左子 2,右子 3。
- 善用斷點觀察遞歸調用棧,確認指針賦值是否生效。