UVA 548 Tree

#include <cstdio>
int min, leaf;

int tree(int root, int *inorder , int *postorder, int sum) {
	if (root == -1) //判断是否无左子结点或右子结点
		return 0;

	sum += postorder[root];
	if (root == 0) { //判断是否为 leaf
		if (sum == min)
			leaf = (postorder[root] < leaf ? postorder[root] : leaf);
		if (sum < min)
			min = sum, leaf = postorder[root];
		return 0;
	}

	int move = root + 1;
	while (inorder[--move] != postorder[root]); //从中序中找出 root 的位置
	tree(move - 1, inorder, postorder, sum); //从 root 的左边寻找左子结点
	tree(root - (move + 1), inorder + (move + 1), postorder + move, sum); //从 root 的右边寻找右子结点
}

int main() {
	int postorder[10050], inorder[10050], root, temp; 

	while (scanf("%d%c", &inorder[root = 0], &temp) != EOF) {
		while (temp != '\n' && scanf("%d%c", &inorder[++root], &temp));
		for (int i = 0; scanf("%d%c", &postorder[i], &temp) && temp != '\n'; i++);
		min = 100000, leaf = 100000;
		tree(root, inorder, postorder, 0);
		printf("%d\n", leaf);
	}
	return 0;
}


你可能感兴趣的:(UVA 548 Tree)