PAT甲级 1043(C++)

代码参考:【题意+分析】1043 Is It a Binary Search Tree (25 分)_来老铁干了这碗代码的博客-CSDN博客

刚开始刷题,这个思路一时半会想不到(悲

#include<iostream>
#include<vector>
using namespace std;
vector<int>preorder;
vector<int>postorder;
vector<int>check;
struct node {
	int element;
	struct node* right;
	struct node* left;
};
void insert(struct node * &  root,int element) {
	if (root == NULL) {
		root = new struct node;
		root->element = element;
		root->right = NULL; root->left = NULL;
		return;
	}
	else if (root->element <= element)
		insert(root->right, element);
	else insert(root->left, element);
}
void pre(struct node* root,int mode) {
	if (root == NULL) return;
	else {
		check.push_back(root->element);
		if (mode == 1) {
			pre(root->left,mode);
			pre(root->right,mode);
		}
		else {
			pre(root->right,mode);
			pre(root->left,mode);
		}
	}
}
void post(struct node * root,int mode) {
	if (root == NULL) return;
	else {
		if (mode == 1) {
			post(root->left, mode); post(root->right, mode);
		}
		else {
			post(root->right, mode); post(root->left, mode);
		}
		postorder.push_back(root->element);
	}
}
int main() {
	int N; cin >> N;
	struct node* root=new struct node;
	for (int i = 1; i <= N; i++) {
		int put; cin >> put; preorder.push_back(put);
		if (i == 1) {
			root->element = put;
			root->left = NULL; root->right = NULL;
		}
		else insert(root, put);
	}
	int flag = 1; int k;
	for (k = 1; k <= 2; k++) {
		check.clear(); pre(root, k);
		for (int i = 0; i < preorder.size(); i++) {
			if (preorder[i] != check[i]) {
				flag = 0;
				break;
			}
			flag = 1;
		}
		if (flag == 1) break;
	}
	if (flag == 0) {
		cout << "NO";
	}
	else {
		post(root,k);
		cout << "YES" << endl;
		for (int i = 0; i < postorder.size(); i++) {
			cout << postorder[i]; 
			if (i != postorder.size() - 1) cout << " ";
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值