ZZU数据结构与算法实验_2
问题描述
用后序遍历的非递归算法输出二叉树上某一结点的所有祖先
solve
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char data;
struct node *lchild, *rchild;
} *BiTree;
//先序建树
void CreatBiTree(BiTree &T) {
char c;
scanf(" %c", &c);
if (c == '#') {
T = NULL;
}
else {
T = new node;
T->data = c;
CreatBiTree(T->lchild);
CreatBiTree(T->rchild);
}
}
//后续非递归遍历找到所求结点后栈内元素即为该结点所有祖先,直接输出即可
void solve(BiTree T, char x) {
if (T != NULL) {
BiTree St[105];
int top = -1;
int i;
BiTree p = T;
BiTree r = NULL;
while (p != NULL || top != -1) {
if (p != NULL) {
St[++top] = p;
p = p->lchild;
}
else {
p = St[top];
if (p->rchild != NULL && p->rchild != r) {
p = p->rchild;
}
else {
if (p->data == x) {
for (i = 0; i < top; i++) {
printf("%c ", St[i]->data);
}
}
p = St[top--];
r = p;
p = NULL;
}
}
}
}
}
int main() {
BiTree T;
CreatBiTree(T); //建树
char x;
scanf(" %c", &x);
solve(T, x); //输出
return 0;
}