1. 程式人生 > 實用技巧 >[PAT] A1043 Is It a Binary Search Tree

[PAT] A1043 Is It a Binary Search Tree

(熟練!重要!)二叉搜尋樹 BST

題目大意

判斷給定序列是否是一個BST或映象BST樹的先序遍歷序列,如果是則輸出該樹的後序遍歷序列。

思路

根據給定序列建立BST樹,求出它的先序遍歷和映象樹的先序遍歷(即原樹遍歷時按照根->右->左),與原序列比較。

AC程式碼

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <cstdio>
#include <vector>
#include <map>
#include<algorithm>
using namespace std;
struct node {
	int key;
	node* lchild;
	node* rchild;
};
vector<int> input, pre1, pre2;
void create(node* &root, int v) {
	if (root == NULL) {
		root = new node;
		root->key = input[v];
		root->lchild = root->rchild = NULL;
		return;
	}
	if (input[v] < root->key)
		create(root->lchild, v);
	else create(root->rchild, v);
}
void preorder(node* p) {
	if (p == NULL)return;
	pre1.push_back(p->key);
	preorder(p->lchild);
	preorder(p->rchild);
}
void mirrorpreorder(node* p) {
	if (p == NULL)return;
	pre2.push_back(p->key);
	mirrorpreorder(p->rchild);
	mirrorpreorder(p->lchild);
}
bool space = false;
void postorder(node* p) {
	if (p == NULL)return;
	postorder(p->lchild);
	postorder(p->rchild);
	if (space == false) {
		printf("%d", p->key);
		space = true;
	}
	else printf(" %d", p->key);
}
void mirrorpostorder(node* p) {
	if (p == NULL)return;
	mirrorpostorder(p->rchild);
	mirrorpostorder(p->lchild);
	if (space == false) {
		printf("%d", p->key);
		space = true;
	}
	else printf(" %d", p->key);
}
int main() {
	int i, n;
	scanf("%d", &n);
	input.resize(n);
	node* root = NULL; //不要漏掉將NULL賦值給root!!!
	for (i = 0;i < n;i++) {
		scanf("%d", &input[i]);
		create(root, i);
	}
	preorder(root);
	mirrorpreorder(root);
	if (pre1 == input) {
		printf("YES\n");
		postorder(root);
	}
	else if (pre2 == input) {
		printf("YES\n");
		mirrorpostorder(root);
	}
	else printf("NO");
	return 0;
}

可以根據BST的特性,不用建立樹直接求。但我沒看懂QAQ...
https://blog.csdn.net/liuchuo/article/details/52160455