好像有点问题。。。但是用测试代码测试 find_ancestors 函数时候,结果没有问题啊?为啥回到main里之后就弄不出来了。。。?
#include <stdio.h>
#include <malloc.h>
typedef struct BTNode
{
int data;
struct BTNode *left, *right;
}BTNode;
BTNode *creat_tree()
{
BTNode *t = NULL;
int x;
//printf ("正在建立一个新二叉树,请输入结点的值:");
scanf ("%d", &x);
if (x == 0) return NULL;
else
{
t = (BTNode *) malloc (sizeof(BTNode));
t -> data = x;
t -> left = creat_tree();
t -> right = creat_tree();
}
return t;
}
//找某个结点的祖先结点方法:对二叉树进行【中】序遍历,当扫描到该结点时,栈中的结点都是祖先结点
//为方便测试,假设各个结点值均不相同
int find_ancestors(BTNode *bt, int x, BTNode *stack[]) //原本 【int x】 应为【BTNode *p】
{
int top = -1;
if (bt != NULL)
{
BTNode *q = bt; //q为工作指针,用于中序遍历
while(q != NULL || top != -1)
{
while (q!=NULL && q->data != x)
{
stack[++top] = q;
q=q->left;
}
if (q->data == x)
return top;
else
{
if (top != -1)
{
q = stack[top--];
q = q->right;
}
}
}
}
return top;
}
int main()
{
BTNode *tree = creat_tree();
int px=0, qx=0;
printf("请输入待操作的结点p的结点值:");
scanf("%d", &px);
printf("请输入待操作的结点q的结点值:");
scanf("%d", &qx);
BTNode *stack1[100]; int top1;
BTNode *stack2[100]; int top2;
top1 = find_ancestors(tree, px, stack1);
top2 = find_ancestors(tree, qx, stack2);
for (int i = top1; i>=0; --i)
{
printf("%d", stack1[i]->data);
for (int j = top2; j>=0; --j)
{
printf("%d", stack2[j]->data);
if (stack1[i]->data == stack2[j]->data)
printf("%d", stack1[i]->data);
break;
}
}
return 0;
}
//用于测试 find_ancestors函数是否正确,可删掉
/*
int main()
{
BTNode *tree = creat_tree();
BTNode *stack[100];
int x=0;
printf("请输入待操作的结点的值:");
scanf("%d", &x);
int top = find_ancestors(tree, x, stack);
for (int i=0; i<=top; ++i)
printf("%d\n", stack[i]->data);
return 0;
}
*/