二叉搜索树(两个是否为同一个??)

解题思路:


输入:5 6 7 4 3 2
pre:5 4 3 2 6 7
in:2 3 4 5 6 7
posts:2 3 4 7 6 5

输入:5 4 3 2 6 7
pre:5 4 3 2 6 7
in:2 3 4 5 6 7
post:2 3 4 7 6 5

输入:5 7 6 3 4 2
pre:5 3 2 4 7 6
in:2 3 4 5 6 7
post:2 4 3 6 7 5

.

两个相同数字的排序二叉树的中序遍历一定是相同的,是从小到大排列

我们只需要遍历比较两个二叉树的前序遍历或者后序遍历即可,比较每个位置的元素是否相同。

中+前  中+后 可以确定是否为同一个数。

题目描述

判断两序列是否为同一二叉搜索树序列

输入描述:

开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。

输出描述:

如果序列相同则输出YES,否则输出NO

示例1

输入

2
567432
543267
576342
0

输出

YES
NO
#include <iostream>
#include <cstdlib>
using namespace std;

string oriRes;
string contrastRes;


typedef struct Node {
	int data;
	struct Node* pLeftChild;
	struct Node* pRightChild;
} Node, * PNode;


void insert(PNode& pT,int k) {
	if (pT == NULL) {
		pT = (PNode)malloc(sizeof(Node));
		pT->data = k;
		pT->pLeftChild = pT->pRightChild = NULL;
		return ;
	}
	int value = pT->data;
	if (k == value) {
		return ;
	} else if (k < value) {
		insert(pT->pLeftChild, k);
	} else {
		insert(pT->pRightChild, k);
	}

}


void preorder(PNode pT,string& str) {
	if (pT == NULL) {
		return ;
	}
	str += ('0' + pT->data);
	preorder(pT->pLeftChild,str);
	preorder(pT->pRightChild,str);

}

int main() {
	int n;

	string ori;
	string contrast;

	PNode pT = NULL;
	PNode pT2 = NULL;
	while(cin >> n && n != 0) {
		// 输入用于参照的string ori并且 建立好搜索二叉树pT,先序遍历存储在oriRes;
		cin >> ori;
		pT = NULL;
		oriRes = "";
		for (int i = 0; i <= ori.size() - 1; i ++) {
			insert(pT,ori[i] - '0');
		}
		preorder(pT,oriRes);


		// 输入用于对比的string contrast 并且建立好搜索二叉树pT2,先序遍历存储在contrastRes;
		for (int i = 1; i <= n; i++) {
			cin >> contrast;
			pT2 = NULL;
			contrastRes = "";
			for (int j = 0; j <= contrast.size() - 1; j++ ) {
				insert(pT2,contrast[j] - '0');
			}
			preorder(pT2,contrastRes);

			// 对比
			if (oriRes == contrastRes) {
				cout << "YES" << endl;
			} else {
				cout << "NO" << endl;
			}

		}


	}



}
发布了123 篇原创文章 · 获赞 1 · 访问量 5455

猜你喜欢

转载自blog.csdn.net/bijingrui/article/details/104851709