I use the iterate function to solve this problem.
when the rood have a left child or a right child, we just call the function to calculate the max value of the subtree.
But we must pay attention to the return value. It is not the current max value. It is the biggest value of root and left child path, root and right child path , root itself(because both the left child and the right child might be negative)
the whole code is attached.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//I did not understand the question clearly, this is a distanse problem in random two nodes
//thus, we can use the iterate method to sove this problem and we should pay attention to the
//return value.
class Solution {
public:
int max_num = -10000;
int maxPathSum2(TreeNode *root)
{
int templeft = 0;
int tempright = 0;
int value = root->val;
int value2 = value;
if(value>max_num)
max_num = value;
if(root->left == NULL && root->right == NULL)
return value;
if(root->left!=NULL)
{
templeft = maxPathSum2(root->left);
if(templeft >0)
value += templeft;
}
if(root->right!=NULL)
{
tempright = maxPathSum2(root->right);
if(tempright > 0)
value += tempright;
}
if(value > max_num) max_num = value;
int ret = 0;
ret = max(value2,max(value2 + templeft,value2 + tempright));//here as we know, the leftchild and the rightchild are both probably be negative, so ret is the value of three options, the right child and the right child and the root it self.
return ret;
}
int maxPathSum(TreeNode *root) {
if(root == NULL)
return 0;
maxPathSum2(root);
return max_num;
}
};