改进这段代码。void AllPath2(BTNode* b) { BTNode* st[MaxSize]; int top = -1; BTNode* p, * r; bool flag; p = b; do { while (p != NULL) { top++; st[top] = p; p = p->lchild; } r = NULL; flag = true; while (top >= -1 && flag) { p = st[top]; if (p->rchild==r) { if (p->lchild == NULL && p->rchild == NULL) { printf("%c到根结点逆路径:", p->data); for (int i = top; i > 0; i--) printf("%c->", st[i]->data); printf("%c\n", st[0]->data); } top--; r = p; } else { p = p->rchild; flag = false; } } } while (top > -1); }
时间: 2023-06-24 17:03:18 浏览: 88
1_BD_allpath.R.r
void AllPath2(BTNode* b) {
BTNode* st[MaxSize];
int top = -1;
BTNode* p = b;
BTNode* r = NULL; // 初始化为NULL
bool flag;
while (p != NULL || top != -1) { // 使用while循环替代do-while循环
while (p != NULL) {
top++;
st[top] = p;
p = p->lchild;
}
p = st[top];
if (p->rchild != NULL && p->rchild != r) { // 修改if条件判断
p = p->rchild;
flag = false;
} else {
if (p->lchild == NULL && p->rchild == NULL) {
printf("%c到根结点逆路径:", p->data);
for (int i = top; i >= 0; i--)
printf("%c->", st[i]->data);
printf("\n");
}
top--;
r = p;
p = NULL; // 修改指针p的值
flag = true;
}
}
}
阅读全文