leetCode 124. the first idea is recursive from root to bottom leaf, and return the max from left or right at each node.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int(TreeNode* node)
{
int max_left = 0, max_right =0;
if(node->left)
max_left = subsum(node->left);
else
returnstd::max(node->val, subsum(node->right));
if(node->right)
max_right = subsum(node->right);
else
returnstd::max(node->val, subsum(node->left));
sum += node->val + std::max(max_left, max_right);
return sum;
}
this will get the max sum branch from top to bottom, but can’t consider the other branch, and there is case when the max sum branch is actually smaller than a subtree sum. so here needs to consider the subtree sum as well, since the root tree can be consider as a subtree, so after implmenting subtree sum, actually no need to consider the other branch sum.
passing priority_queue s as reference, so if subtree_sum is bigger than the top-bottom branch sum, then it will be pushed into s; but pop out the elements smaller than current branch sum in each recrusive routing.
finally, compare the largest elemnet in s with top-bottom branch sum.
近期评论