5-4 是否同一棵二叉搜索树 (25分)

#include <iostream>

using namespace std;

struct node
{
	int lchild, rchild, key;
}tree1[10], tree2[10];

int index = -1;

void initnode(node tree[], int root, int key)
{
	tree[root].key = key;
	tree[root].lchild = tree[root].rchild = -1;
}

void buildtree(node tree[], int root, int key)
{
	if(index == -1)
	{
		initnode(tree, ++index, key);
		return;
	}

	int rootkey = tree[root].key, l = tree[root].lchild, r = tree[root].rchild;
	if(key < rootkey)
	{
		if(l == -1)
		{
			tree[root].lchild = ++index;
			initnode(tree, index, key);
		}
		else
		{
			buildtree(tree, l, key);
		}
	}
	else
	{
		if(r == -1)
		{
			tree[root].rchild = ++index;
			initnode(tree, index, key);
		}
		else
		{
			buildtree(tree, r, key);
		}
	}
}

int judge(int root1, int root2)
{
	if(root1 == -1 && root2 == -1)
	{
		return 1;
	}
	if(root1 == -1 || root2 == -1)
	{
		return 0;
	}
	if(tree1[root1].key != tree2[root2].key)
	{
		return 0;
	}

	int l = judge(tree1[root1].lchild, tree2[root2].lchild);
	int r = judge(tree1[root1].rchild, tree2[root2].rchild);
	return l && r;
}

void inittree(int n, node tree[])
{
	int i;
	for(i = 0; i < n; i++)
	{
		tree[i].lchild = tree[i].rchild = -1;
	}

	index = -1;
}

int main()
{
	int n, m, i, j, key;
	while(scanf("%d", &n) && n > 0)
	{
		scanf("%d", &m);
		m++;

		for(i = 1; i <= m; i++)
		{
			if(i == 1)
			{
				inittree(n, tree1);
			}
			else
			{
				inittree(n, tree2);
			}

			for(j = 1; j <= n; j++)
			{
				scanf("%d", &key);

				if(i == 1)
				{
					buildtree(tree1, 0, key);
				}
				else
				{
					buildtree(tree2, 0, key);
				}
			}

			if(i > 1)
			{
				if(judge(0, 0) == 1)
				{
					printf("Yes\n");
				}
				else
				{
					printf("No\n");
				}
			}
		} 
	}

	system("pause");
	return 0;
}

 

posted on 2025-11-29 14:56  王景迁  阅读(0)  评论(0)    收藏  举报

导航