04-树4 是否同一棵二叉搜索树

**

04-树4 是否同一棵二叉搜索树

**
思路:先建一个“样板树”,随后让数据下至树内。若与样板树的结构一致,则为真。

#include <iostream>
#include <vector>
using namespace std;
struct Tree {
	int val=0;
	Tree* left=NULL;
	Tree* right=NULL;
	bool flag = 0;//flag标记有没有来到过这个节点
};
bool checkVal(Tree* root, int treeVal)
{
	if (root->flag)
	{
		if (treeVal < root->val)
			return checkVal(root->left, treeVal);
		if (treeVal > root->val)
			return checkVal(root->right, treeVal);
	}
	else
	{
		if (root->val == treeVal)
		{
			root->flag = 1;
			return 1;
		}
		return 0;
	}
}
void resetTreeFlag(Tree* root)
{//先序遍历重置树的所有节点上的flag值。
	if (!root)
		return;
	root->flag = 0;
	resetTreeFlag(root->left);
	resetTreeFlag(root->right);
}
bool isSameTree(Tree* root, vector<int> treeVal)
{
	resetTreeFlag(root);
	for (auto& it : treeVal)
	{
		if (!checkVal(root, it))
			return 0;//若有任何一个节点不符合原来的树就返回假
	}
	return 1;
}


Tree* addTreeNode(Tree* root, int val)
{
	if (!root)
	{
		Tree* newTree = new Tree;
		newTree->val = val;
		return newTree;
	}
	if (val > root->val)
	{
		root->right = addTreeNode(root->right,val);
		return root;
	}
	else if (val < root->val)
	{
		root->left =  addTreeNode(root->left, val);
		return root;
	}
}
int main()
{
	int N;
	cin >> N;
	int L;
	while (N)
	{
		cin >> L;
		Tree *iniRoot =NULL;
		for (int i = 0; i < N; i++)
		{
			int val;
			cin >> val;
			iniRoot = addTreeNode(iniRoot, val);
		}
		
		for (int i = 0; i < L; i++)
		{
			vector<int> treeVal;
			for (int i = 0; i < N; i++)
			{
				int val;
				cin >> val;
				treeVal.push_back(val);
			}
			if (isSameTree(iniRoot, treeVal))
				cout << "Yes" << endl;
			else	
				cout << "No" << endl;
		}
		cin >> N;
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值