1043. Is It a Binary Search Tree 解析

按先序的顺序建搜索树,然后先序遍历和先序比对,如果不一样再按NRL的顺序遍历比对。

#include <iostream>
#include <vector>

#define MAX 1010

using namespace std;

int list[MAX];
int N;
struct Node {
	int data;
	Node * l;
	Node * r;
	Node() { data = -1; l = NULL; r = NULL; }
};

typedef Node * Tree;
vector <int> pre;
vector <int> preCheck;
vector <int> post;


void builTree(int num ,Tree &t) {
	if (t == NULL) {
		t = new Node;
		t->data = num;
	}
	else if(num < t->data && t->data >0){
		builTree(num, t->l);
	}
	else if (num >= t->data && t->data > 0) {
		builTree(num, t->r);
	}
	else
		return;
}

void preOreder(Tree t) {
	if (t) {
		preCheck.push_back(t->data);
		preOreder(t->l);
		preOreder(t->r);
	}
}

void preOrederM(Tree t) {
	if (t) {
		preCheck.push_back(t->data);
		preOrederM(t->r);
		preOrederM(t->l);		
	}
}

void postOreder(Tree t) {
	if (t) {		
		postOreder(t->l);
		postOreder(t->r);
		post.push_back(t->data);
	}
}

void postOrederM(Tree t) {
	if (t) {		
		postOrederM(t->r);
		postOrederM(t->l);
		post.push_back(t->data);
	}
}


void printV() {
	for (int i = 0; i < post.size() - 1; i++) {
		cout << post[i] << " ";
	}
	cout << post[post.size() - 1] << endl;
}

int main() {
	cin >> N;
		
	Tree T = NULL;

	int temp;
	for (int i = 0; i < N; i++) {
		cin >> temp;
		builTree(temp, T);
		pre.push_back(temp);	
	}

	bool tag = true;
	preOreder(T);
	for (int i = 0; i < pre.size(); i++) {
		if (pre[i] != preCheck[i])
			tag = false;
	}
	if (tag) {
		postOreder(T);
		cout << "YES" << endl;
		printV();
		return 0;
	}
	


	//镜像
	tag = true;
	preCheck.clear();

	preOrederM(T);
	for (int i = 0; i < pre.size(); i++) {
		if (pre[i] != preCheck[i])
			tag = false;
	}
	if (tag) {
		postOrederM(T);
		cout << "YES" << endl;
		printV();
		return 0;
	}
	else {
		cout << "NO" << endl;
	}



	system("pause");

	return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值