1、题目描述
给出一颗二叉树,每个节点有一个编号和个值,该值可能为负数,请你找出个最优节点(除根节点外),使得在该节点将树分成两棵树后(原来的树移除这个节点及其子节点,新的树以该节点为根节点),分成的两棵树各节点的和之间的差绝对值最大。请输出该节点编号,如有多个相同的差,输出编号最小的节点。
2、示例
输入:
4
4 9 -7 -8
0 1
0 3
1 2
第一行,四个节点,编号0-3,范围1-10000
第二行,节点0-3权值
第三行到第五行,表示二叉树各节点间的父子关系
0 1 节点0的左节点是1
0 3 节点0的右节点是3
1 2 节点1的左节点是2
注意:左节点永远出现在右节点之前
输出:
节点编号,示例中编号为3的节点是最优节点
3、题解
基本思想:递归,先递归求出每个节点的子树节点之和,然后遍历每个节点,求出diffvalue=abs(node.second.sum*2-sum)是否大于maxdiffvalue,如果是更新maxdiffvalue以及targetnode。
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include<math.h>
using namespace std;
struct node{
int num_child;
int value;
int sum;
int child[2];
};
int sum=0;
map<int,node> node_map;
int caculate_sum(int root)
{
int ret=node_map[root].value;
for(int i=0;i<node_map[root].num_child;i++)
{
int x=caculate_sum(node_map[root].child[i]);
ret+=x;
}
node_map[root].sum=ret;
return ret;
}
int main()
{
int n,root;
vector<bool> isroot;
cin>>n;
isroot=vector<bool>(n,true);
node tmp;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
node_map[i].num_child=0;
node_map[i].value=x;
sum+=x;
}
for(int i=0;i<n-1;i++)
{
int fa,child;
cin>>fa>>child;
isroot[child]=false;
node_map[fa].child[node_map[fa].num_child++]=child;
}
for(int i=0;i<n;i++)
{
if(isroot[i])
{
root=i;
break;
}
}
caculate_sum(root);
int maxm=0;
int index=0;
for(auto &i:node_map)
{
int cha=2*i.second.sum-sum;
if(maxm<abs(cha)){
maxm=abs(cha);
index=i.first;
}
else if(maxm==abs(cha)&&i.first<index)
{
index=i.first;
}
}
cout<<index<<endl;
return 0;
}