PTA-是否同一棵二叉搜索树

本文介绍了如何使用C++实现二叉树的结构、新建节点、插入操作,以及先序和中序遍历。作者通过实例展示了如何通过先序和中序遍历数组来确定一棵树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

结合了树的构建,遍历输出,指针的传递等知识点

写了一个多小时的shi山代码,暂时没精力总结和修改了,等以后再优化一下吧、

累了。。。

#include<iostream>
using namespace std;

struct tree
{
	int data;
	tree* right;
	tree* left;
};

void tree_new(tree* &add,int n)//新建节点
{
	add = new tree;
	add->data = n;
	add->left = NULL;
	add->right = NULL;

}

void tree_insert(tree* &p,tree*& add)//树的插入
{

	if (p->data > add->data)
	{
		if (p->left != NULL)
		{
			tree_insert(p->left, add);
		}
		else
		{
			p->left = add;
		}
		
	}
	else
	{
		if (p->right != NULL)
		{
			tree_insert(p->right, add);
		}
		else
		{
			p->right = add;
		}
	}
}

//还差数组元素的控制实现
int cnt2 = 0;
int cnt1 = 0;

void tree_xian(tree*& p,int *&xian)//先序遍历
{
	if (p)
	{
		tree_xian(p->left,xian);//递归调用		
		xian[cnt1++] = p->data;
		tree_xian(p->right, xian);
	}
	return;
}																													   

void tree_zhong(tree*& p, int*& zhong)//中序遍历
{
	if (p)
	{
		zhong[cnt2++] = p->data;
		tree_zhong(p->left, zhong);//递归调用		
		tree_zhong(p->right, zhong);
	}
	return;
}

void tree_back(tree*& p, int*& xian, int*& zhong)//返回先序和中序遍历的结果数组
{
	//因为需要两种遍历才能唯一确定一棵树
	//所以这里用xian[]来储存先序遍历的结果,用zhong[]来存储中序遍历的结果
	tree_xian(p, xian);
	tree_zhong(p, zhong);


}





int main()
{
	//输入2个值
	int n, l;
	tree* yuan_add = NULL;
	tree* yuan_p = NULL;
	cin >> n ;
	while (n != 0)
	{
		cin >> l;
	int tmp;
	cin >> tmp;
	tree_new(yuan_p, tmp);
	for (int i = 1; i < n; i++)
	{
		cin >> tmp;
		tree_new(yuan_add, tmp);
		tree_insert(yuan_p, yuan_add);
	}
	cnt1 = 0;
	cnt2 = 0;
	int* yuan_xian;
	yuan_xian = new int[n];
	int* yuan_zhong;
	yuan_zhong = new int[n];
	tree_back(yuan_p, yuan_xian, yuan_zhong);
	//测试
	/*for (int i = 0; i < n; i++)
	{
		cout << yuan_xian[i] << endl;
	}
	cout << endl;
	for (int i = 0; i < n; i++)
	{
		cout << yuan_zhong[i] << endl;
	}*/

	for (int i = 0; i < l; i++)
	{
		tree* add = NULL;
		tree* p = NULL;
		int tmp;
		cin >> tmp;
		tree_new(p, tmp);
		for (int i = 1; i < n; i++)
		{
			cin >> tmp;
			tree_new(add, tmp);
			tree_insert(p, add);
		}
		cnt1 = 0;
		cnt2 = 0;
		int* xian;
		xian = new int[n];
		int* zhong;
		zhong = new int[n];
		tree_back(p, xian, zhong);


		int flag = 0;
		for (int j = 0; j < n; j++)
		{
			if (xian[j] != yuan_xian[j])
			{
				cout << "NO" << endl;
				flag = 1;
				break;
			}
			if (zhong[j] != yuan_zhong[j])
			{
				cout << "NO" << endl;
				flag = 1;
				break;
			}

		}
		if (flag == 0)
		{
			cout << "YES" << endl;
		}

	}
	cin >> n;

	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值