判断两棵二叉树是否相似。

按先序遍历序列建立两个二叉树的二叉链表 A 和链表 B ,设计算法判断 A 、 B 二叉树是否相似。

注:其中“#”表示的是空格,空格字符代表空树。
测试用例1

ab#c##d##↵
xc#v##b##↵

期待输出1

A与B相似↵
#include   
#include   
#include   

using namespace std;

string treeA;
string treeB;
int lenA;
int lenB;
int curIndex = 0;
int layer;

struct tree
{
public:
	char data;
	tree *left;
	tree *right;
};

void CreateTreeA(int curLayer, tree *node);
void CreateTreeB(int curLayer, tree *node);
bool Equal(tree* nodeA, tree* nodeB);

int main()
{
	cin >> treeA;
	cin >> treeB;

	lenA = treeA.size();
	lenB = treeB.size();

	int power = 0;
	while (((2 << power) - 1) < lenA)
	{
		power++;
	}
	layer = power + 1;
	tree *TreeA = new tree;
	CreateTreeA(1, TreeA);

	power = 0;
	while (((2 << power) - 1) < lenB)
	{
		power++;
	}
	layer = power + 1;
	curIndex = 0;
	tree *TreeB = new tree;
	CreateTreeB(1, TreeB);

	if (Equal(TreeA, TreeB))
	{
		cout << "A与B相似" << endl;
	}
	else
	{
		cout << "A与B不相似" << endl;
	}
	return 0;
}

void CreateTreeA(int curLayer, tree *node)
{
	if (treeA[curIndex] != '#')
	{
		node->data = treeA[curIndex++];
	}
	else
	{
		curIndex++;
	}

	if (node->left == NULL && curIndex < lenA && curLayer + 1 <= layer)
	{
		tree *tmp = new tree;
		node->left = tmp;
		tmp->data = ' ';
		tmp->left = NULL;
		tmp->right = NULL;
		CreateTreeA(curLayer + 1, node->left);
	}
	if (node->right == NULL && curIndex < lenA && curLayer + 1 <= layer)
	{
		tree *tmp = new tree;
		node->right = tmp;
		tmp->data = ' ';
		tmp->left = NULL;
		tmp->right = NULL;
		CreateTreeA(curLayer + 1, node->right);
	}
}

void CreateTreeB(int curLayer, tree *node)
{
	if (treeB[curIndex] != '#')
	{
		node->data = treeB[curIndex++];
	}
	else
	{
		curIndex++;
	}

	if (node->left == NULL && curIndex < lenB && curLayer + 1 <= layer)
	{
		tree *tmp = new tree;
		node->left = tmp;
		tmp->data = ' ';
		tmp->left = NULL;
		tmp->right = NULL;
		CreateTreeB(curLayer + 1, node->left);
	}
	if (node->right == NULL && curIndex < lenB && curLayer + 1 <= layer)
	{
		tree *tmp = new tree;
		node->right = tmp;
		tmp->data = ' ';
		tmp->left = NULL;
		tmp->right = NULL;
		CreateTreeB(curLayer + 1, node->right);
	}
}

bool Equal(tree* nodeA, tree* nodeB)
{
	if (nodeA == NULL && nodeB == NULL)
	{
		return true;
	}
	if ((nodeA == NULL && nodeB != NULL) || (nodeA != NULL && nodeB == NULL))
	{
		return false;
	}
	if ((nodeA->data == ' '&&nodeB->data == ' ') || nodeA->data != ' '&&nodeB->data != ' ')
	{
		return Equal(nodeA->left, nodeB->left) && Equal(nodeA->right, nodeB->right);
	}
	else
	{
		return false;
	}
}

你可能感兴趣的:(C++习题实践)