//@author zengkui111@gmail.com
struct node
{
int node_id;
int number;
bool has_negative_node;
int sum_of_subtree;
struct node *left;
struct node *right;
};
// the return value is the node id which the sum of the subtree is max , -1 is not find
int find_max_sum_of_subtree( struct node *root, const bool &negative_is_ok )
{
if ( NULL == root -> left and NULL == root->right )
{
//leaf node
root->sum_of_subtree = root->number;
if ( root->number < 0 )
{
root->has_negative_node = true;
}
if ( !negative_is_ok )
{
if ( root->number > 0 )
{
return node_id;
}
else
{
//not find any node
return -1;
}
}
return root->node_id;
}
//The max sum of subtree is from left child or right child or this whole subtree
root->sum_of_subtree = root->number;
int left_id = -1;
int right-id = -1;
root->has_negative_root = false;
if ( root->number < 0 )
{
root->has_negative_root = true;
}
if ( root -> left )
{
left_id = find_max_sum_of_subtree ( root->left, negative_is_ok );
root->sum_of_subtree += root->left->sum_of_subtree;
if ( root->left->has_negative_root )
{
root->has_negative_root = true;
}
}
if( root -> right )
{
right_id = find_max_sum_of_subtree ( root->right, negative_is_ok );
root->sum_of_subtree += root->right->sum_of_subtree;
if ( root->right->has_negative_root )
{
root->has_negative_root = true;
}
}
int max_sum = (1<<31);
int node_idx = -1;
if ( ! negative_is_ok )
{
if ( root->sum_of_subtree > max_sum and !root->has_negative_root )
{
max_sum = root->sum_of_subtree;
node_idx = root->node_id;
}
if ( root->left and root->left->sum_of_subtree > max_sum and !root->left->has_negative_root )
{
max_sum = root->left->sum_of_subtree;
node_idx = root->node_id;
}
if ( root->right and root->right->sum_of_subtree > max_sum and !root->right->has_negative_root )
{
max_sum = root->right->sum_of_subtree;
node_idx = root->node_id;
}
return node_idx;
}
if ( root->sum_of_subtree > max_sum)
{
max_sum = root->sum_of_subtree;
node_idx = root->node_id;
}
if ( root->left and root->left->sum_of_subtree > max_sum)
{
max_sum = root->left->sum_of_subtree;
node_idx = root->node_id;
}
if ( root->right and root->right->sum_of_subtree > max_sum)
{
max_sum = root->right->sum_of_subtree;
node_idx = root->node_id;
}
return node_idx;
}