@【数据结构】(二叉树-求祖先节点)
设计一个算法,求给定值x的结点在二叉树中的所有祖先,设树中值为x的结点不多于一个。
#include<stdio.h>
#include<iostream>
using namespace std;
#define MAX 100
typedef char Elemtype;
typedef struct tNode
{
Elemtype data;
struct tNode *lchild, *rchild;
}BiTNode, *BiTree;
BiTNode *createtree()
{
BiTNode *T;
char str;
str = getchar();
if (str == '#')
return NULL;
else
{
T = (BiTNode*)malloc(sizeof(BiTNode));
T->data = str;
T->lchild = createtree();
T->rchild = createtree();
return T;
}
}
void ancestor(BiTNode *bt, Elemtype x,Elemtype path[], int l)
{
int i;
if (bt != NULL)
{
if (bt->lchild == NULL && bt->rchild == NULL)
{
if (bt->data == x)
{
cout << bt->data << "结点的所有祖先结点为:";
for (i = l - 1; i >= 0; i--)
cout << path[i];
cout << endl;
}
}
else
{
path[l] = bt->data;
l++;
}
ancestor(bt->lchild,x, path, l);
ancestor(bt->rchild,x, path, l);
}
}
void main()
{
Elemtype x;
BiTNode *p;
Elemtype path[MAX];
cout << "创建二叉树" << endl;
cout << "请以先序输入节点的值,为空时输入'#':" << endl;
BiTNode *bt = createtree();
cout << "输入结点值:";
cin >> x;
ancestor(bt, x, path, 0);
system("pause");
}
测试二叉树:
结果: