Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

       1
      / \
     2   3

 

Return 6.

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int DFS(struct TreeNode *root, int* maxSubSum){
    if(root == NULL)
        return 0;
    int leftPathSum = 0;
    int rightPathSum = 0;
    int result = 0;
    if(root->left != NULL){
        leftPathSum = DFS(root->left, maxSubSum);
    }
    if(root->right != NULL)
        rightPathSum = DFS(root->right, maxSubSum);
   
    result = root->val +(leftPathSum >=0 ? leftPathSum : 0 ) + (rightPathSum >= 0 ? rightPathSum : 0);
    *maxSubSum = *maxSubSum > result ? *maxSubSum : result;
    
    result = leftPathSum > rightPathSum ? leftPathSum : rightPathSum;  
    return result > 0 ? result + root->val : root->val;  //不一定要到叶子
} 
 
int maxPathSum(struct TreeNode* root) {
    // left and right, every time refresh the maxpath,and return the max left or right
    int maxSubSum = 0;
    int leftPathSum = 0;
    int rightPathSum = 0;
    int result = 0;
    if(root == NULL)
        return 0;
    maxSubSum = root->val;
    DFS(root, &maxSubSum);    
    return maxSubSum;
}
  • 注意题目中不需要达到叶子,也不需要根

你可能感兴趣的:(Binary Tree Maximum Path Sum)