其他分享
首页 > 其他分享> > Tree UVA - 548

Tree UVA - 548

作者:互联网

  You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of nodes along that path.

Input

  The input file will contain a description of the binary tree given as the inorder and postorder traversal sequences of that tree. Your program will read two line (until end of file) from the input file. The first line will contain the sequence of values associated with an inorder traversal of the tree and the second line will contain the sequence of values associated with a postorder traversal of the tree. All values will be different, greater than zero and less than 10000. You may assume that no binary tree will have more than 10000 nodes or less than 1 node.

Output

  For each tree description you should output the value of the leaf node of a path of least value. In the case of multiple paths of least value you should pick the one with the least value on the terminal node.

Sample Input

3 2 1 4 5 7 6
3 1 2 5 6 7 4
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
255
255

Sample Output

1
3
255

HINT

主要难点就是建树和输出。建树采用的是递归的方式,使用map记录中序数组的下标便于查找,关键的是如何来递归,尤其要注意如何来划分左子树和右子树。具体操作看代码就好。

而输出就是一个查找,直到找到叶子结点,查到最短最小的,然后输出。其他的都是不断累加查找。

Accepted

#include<iostream>
#include<algorithm>
#include<map>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<sstream>
#include<fstream>
using namespace std;
vector<int>mid, pos;
map<int, int>id;
int maxx = 0x3fffff,ans=-1;


struct TREE{
	int num;
	TREE* left, * right;
};

TREE* build(int &i,int star,int end) {
	if (star>end)return NULL;
	TREE* head = new TREE;
	head->num = pos[i];
	head->left = head->right = NULL;
	int p = id[pos[i]];		//找到在中序遍历中的位置
	i--;
	head->right = build(i, p + 1, end);
	if (head->right != NULL)i--;		//如果确实插入了就减一
	head->left = build(i, star, p - 1);	
	if (!head->left)i++;				//如果没有插入就加一
	return head;						//返回头指针
}

void dfs(TREE* head, int sum) {
	if (!head->left && !head->right) {
		sum += head->num;
		if (sum < maxx || (sum == maxx && ans > head->num)) {
			maxx = sum;
			ans = head->num;
		}
		return;
	}
	if (head->left)dfs(head->left, head->num + sum);
	if (head->right)dfs(head->right, head->num + sum);
}

int main(){
	int t1,t2;
	string s,s1,s2;
	while (getline(cin, s1)) {
		getline(cin, s2);
		mid.clear();pos.clear();id.clear();
		stringstream ss1(s1), ss2(s2);
		while (ss1>>t1&&ss2>>t2){
			mid.push_back(t1);
			pos.push_back(t2);
			id[t1] = mid.size() - 1;
		}
		int size = pos.size() - 1;
		TREE* head = build(size, 0, mid.size() - 1);
		maxx = 0x3fffff;
		dfs(head, 0);
		cout << ans << endl;

	}
}

标签:TREE,head,int,tree,sum,Tree,UVA,548,include
来源: https://www.cnblogs.com/3236676588buladuo/p/14392589.html