@【数据结构】(二叉树-求祖先节点)

@【数据结构】(二叉树-求祖先节点)

设计一个算法,求给定值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");
}

测试二叉树:
在这里插入图片描述
结果:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值