Binary Tree Maximum Path Sum C++


  • 0
    S
    /**
     * 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 rslt = 0x80000000;
            
            maxPathSumUtil(root, rslt);
            
            return rslt;
        }
        
        int maxPathSumUtil(TreeNode* root, int &rslt) {
            if (root == NULL) {
                return 0;
            }
            
            int l = maxPathSumUtil(root->left, rslt);
            int r = maxPathSumUtil(root->right, rslt);
            
            int max_single = maxOf(maxOf(l, r) + root->val, root->val);
            
            int max_top = maxOf(max_single, l + r + root->val);
            
            rslt = maxOf(max_top, rslt);
    
            return max_single;
        }
        
        int maxOf(int a, int b) {
            if (a >= b) {
                return a;
            }
            
            return b;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.