URAL 1136 Parliament 二叉树水题 BST后序遍历建树

二叉树水题,特别是昨天刚做完二叉树用中序后序建树,现在来做这个很快的。

跟昨天那题差不多,BST后序遍历的特型,找到最后那个数就是根,向前找,比它小的那块就是他的左儿子,比它大的那块就是右儿子,然后递归儿子继续建树。


代码:


#include <cstdio>
#include <cstdlib>
const int maxn = 70000;

struct Node {
	int v;
	Node *l;
	Node *r;
};
int arr[maxn];
bool flag = false;

Node* addnode(int s, int e) {
	if (s > e)
		return NULL;
	Node* u = (Node*) malloc (sizeof(Node*));
	u->v = arr[e];
	if (s == e) {
		u->r = u->l = NULL;
		return u;
	}
	int i;
	for (i = e - 1; i >= s; i--)
		if (arr[i] < arr[e])
			break;
	u->l = addnode(s, i);
	u->r = addnode(i + 1, e - 1);
	return u;
}

void output(Node* u) {
	if (u->r != NULL)
		output(u->r);
	if (u->l != NULL)
		output(u->l);
	if (flag)
		printf(" ");
	flag = true;
	printf("%d", u->v);
}

int main() {
	int n;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
		scanf("%d", &arr[i]);
	Node* root = addnode(1, n);
	output(root);
	printf("
");
	return 0;
}
	




原文地址:https://www.cnblogs.com/snake-hand/p/3180270.html