*leetcode #124 in cpp

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.

Solution:

This question is pretty hard. I did not figure it out until I searched for solution online. 

Code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxPathSum(TreeNode* root) {
        int maxx = INT_MIN;
        findMaxPathSum(root, maxx);
        return maxx; 
    }
    int findMaxPathSum(TreeNode *node,int &maxx){ //this function returns the max path sum from node to its successors i.  
        if(!node) return 0;
        int left = findMaxPathSum(node->left,maxx); 
        int right = findMaxPathSum(node->right,maxx);
        int temp = max(max(node->val, node->val + left),node->val + right);
        maxx = max(max(temp,node->val+left + right), maxx);//record the max sum at node, by comparing max path sum that starts at node, and max path sum that goes from left child to node to right child. 
        return temp;
    }
    
    
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章