您的位置:首页 > 其它

UVA 548 - Tree

2017-09-03 17:59 302 查看
题目大意:给你二叉树的中序遍历,和后序遍历的结果。让你求,权值最小的叶子节点。也就是从根到叶子结点的值的和最小的点。如果权值相等,输出叶子节点值较小的点。

解题思路:由后序遍历得到根节点的值。即后序遍历最后一个为根,然后在中序遍历中查找这个根的值的位置,左边为左子树,右边为右子树。针对左子树也是同样操作,找“根”(左子树的全体作为树),根的左右子树。也就是递归求树。建树。这是第一题完全自己做得...刚开始以为是求最小叶子节点,后面根据写完的代码,改一下就有了树,所以这里我不会讲思路的。美滋滋。欢迎一起讨论

ac代码:
#include <iostream>
#include <map>
using namespace std;
multimap <int, int>ma;
map <int, int>::iterator it;
int a[10005], b[10005], count;
using namespace std;

struct tree{
int data;
int sum;
tree *left;
tree *right;
tree()
{
data = sum = 0;
left = right = NULL;
}
}; 
tree *ro;
tree* dfs(int m, int n, int t, int k, tree* ro)
{
int root=b
;
tree *node;
node = new tree;
node->data = root;
node->sum = ro->sum + root;
if (k-t == 1){
ma.insert(make_pair(node->sum, node->data));
return node;
}
for (int i=t; i<k; i++)
if (a[i] == root){
node->left = dfs(m, m+i-t-1, t, i, node);
node->right = dfs(m+i-t, n-1, i+1, k, node); 
break;
}
}

int input(int a[])
{
char c = getchar();
int i = 1;
while (c != '\n'){
scanf("%d", &a[i++]);
c = getchar();
}
return i;
}
int main()
{
int i;
char c;
while (scanf("%d", &a[0])!=EOF){
ro = new tree;
input(a);
scanf("%d", &b[0]);
count = input(b);
dfs(0, count-1, 0, count, ro);
it=ma.begin();
cout << it->second << endl;
ma.clear();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: