数据结构与算法编程题21

判别两棵树是否相等。

#define _CRT_SECURE_NO_WARNINGS

#include 
using namespace std;

typedef char ElemType;
#define ERROR 0
#define OK 1

typedef struct BiNode
{
	ElemType data;
	BiNode* lchild, * rchild;
}BiNode, * BiTree;

bool Create_tree(BiTree& T)
{
	ElemType x = 0;
	cin >> x;
	if (x == '#')
	{
		T = NULL;
	}
	else
	{
		T = (BiTree)malloc(sizeof(BiNode));
		if (T == NULL)
		{
			cout << "内存无法分配!!!" << endl;
			return ERROR;
		}
		T->data = x;
		T->lchild = NULL;
		T->rchild = NULL;
		Create_tree(T->lchild);
		Create_tree(T->rchild);
	}
	return OK;
}

void PreOrder(BiTree T)
{
	if (T != NULL)
	{
		cout << T->data;
		PreOrder(T->lchild);
		PreOrder(T->rchild);
	}
}

void InOrder(BiTree T)
{
	if (T != NULL)
	{
		InOrder(T->lchild);
		cout << T->data;
		InOrder(T->rchild);
	}
}

void PostOrder(BiTree T)
{
	if (T != NULL)
	{
		PostOrder(T->lchild);
		PostOrder(T->rchild);
		cout << T->data;
	}
}
//---------------------------------核心代码---------------------------------//
bool tree_same(BiTree& T1, BiTree& T2)
{
	if (T1 == NULL && T2 == NULL)
	{
		return OK;
	}
	else if(T1 == NULL || T2 == NULL)
	{
		return ERROR;
	}
	else  //T1 != NULL && T2 != NULL
	{
		if (T1->data != T2->data)
			return ERROR;
		return tree_same(T1->lchild, T2->lchild) && tree_same(T1->rchild, T2->rchild);
	}
}
//---------------------------------核心代码---------------------------------//
//判别两棵树是否相等。
//第一颗树:123##4##5##
//第二颗树:123##4##6##
int main(void)
{
	cout << "//------生成第一颗树---------//" << endl;
	BiTree T1 = NULL;
	Create_tree(T1);
	PreOrder(T1);
	cout << endl;
	InOrder(T1);
	cout << endl;
	PostOrder(T1);
	cout << endl;
	cout << "//------生成第一颗树---------//" << endl;

	cout << "//------生成第二颗树---------//" << endl;
	BiTree T2 = NULL;
	Create_tree(T2);
	PreOrder(T2);
	cout << endl;
	InOrder(T2);
	cout << endl;
	PostOrder(T2);
	cout << endl;
	cout << "//------生成第二颗树---------//" << endl;

	if (tree_same(T1, T2) == OK)
	{
		cout << "两个树相等" << endl;
	}
	else
	{
		cout << "两个二叉树不相等" << endl;
	}
	return 0;
}

数据结构与算法编程题21_第1张图片
数据结构与算法编程题21_第2张图片

你可能感兴趣的:(算法与数据结构,数据结构)