typedef char Tchar;
typedef struct TreeNode {
Tchar data;
struct TreeNode* lchild;
struct TreeNode* rchild;
}BTNode;
typedef BTNode* STDatatype;
typedef struct Stack
{
STDatatype* a;
int top;
int capacity;
}ST;
//建立二叉树
void CreatBTree(BTNode** T) {
char ch;
scanf_s("%c", &ch, 1);
if (ch == '#') {
*T = NULL;
}
else {
*T = (BTNode*)malloc(sizeof(BTNode));
if (*T == NULL) {
return;
}
else {
(*T)->data = ch;
CreatBTree(&(*T)->lchild);
CreatBTree(&(*T)->rchild);
}
}
return;
}
//栈扩容
void Expend(ST* ps) {
assert(ps);
if (ps->top == ps->capacity)
{
int newCapacity = ps->capacity = 0 ? 4: ps->capacity * 2;
STDatatype* tmp = realloc(ps->a, sizeof(STDatatype) * newCapacity);
if (tmp == NULL) {
printf("relloc fail");
exit(-1);
}
ps->a = tmp;
ps->capacity = newCapacity;
}
};
//初始化栈
void STackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->capacity = 0;
ps->top = 0;
};
void STackDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->top = ps->capacity = 0;
ps->a = NULL;
};
//进栈
void STackPush(ST* ps, STDatatype x)
{
assert(ps);
Expend(ps);
ps->a[ps->top] = x;
ps->top++;
};
//出栈
void STackPop(ST* ps) {
assert(ps);
assert(ps->top > 0);
ps->top--;
}
获取栈顶
STDatatype STackTop(ST* ps)
{
assert(ps);
assert(ps->top > 0);
return ps->a[ps->top - 1];
};
bool STackEmpty(ST* ps) {
assert(ps);
return ps->top == 0;
};
//先序遍历
void xian(BTNode* T) {
ST s;
STackInit(&s);
if (T != NULL) {
STackPush(&s, T);
while (!(STackEmpty(&s))) {
BTNode* front = STackTop(&s);
printf("%c ", front->data);
STackPop(&s);
if (T->lchild != NULL) {
STackPush(&s, front->lchild);
}
if (T->rchild != NULL) {
STackPush(&s, front->rchild);
}
}
}
}
//主函数
int main() {
BTNode* T;
CreatBTree(&T);
xian(T);
return 0;
}
报错
在先序遍历函数xian()中,遍历到根节点时应该使用栈顶元素front而不是固定的根节点T来判断左右子树是否为空并将它们入栈,因为在栈中根节点不一定是最上层的元素。
修改建议:
void xian(BTNode* T) {
ST s;
STackInit(&s);
if (T != NULL) {
STackPush(&s, T);
while (!(STackEmpty(&s))) {
BTNode* front = STackTop(&s);
printf("%c ", front->data);
STackPop(&s);
if (front->lchild != NULL) { //判断条件
STackPush(&s, front->lchild);
}
if (front->rchild != NULL) { //判断条件
STackPush(&s, front->rchild);
}
}
}
}
如果答案对您有所帮助,望采纳。