zoukankan      html  css  js  c++  java
  • 【hard】124. Binary Tree Maximum Path Sum

    Given a non-empty 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 must contain at least one node and does not need to go through the root.

    Example 1:

    Input: [1,2,3]
    
           1
          / 
         2   3
    
    Output: 6
    

    Example 2:

    Input: [-10,9,20,null,null,15,7]
    
       -10
       / 
      9  20
        /  
       15   7
    
    Output: 42


    /**
     * 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 {
    private:
        int solution(TreeNode* root, int& best){  // my own solution
            if (!root) return 0;
            int left_sum = root->val + solution(root->left, best);
            int right_sum = root->val + solution(root->right, best);
            int curve_sum = left_sum + right_sum - root->val;
            best = max({best, left_sum, right_sum, curve_sum, root->val});
            
            return max({left_sum, right_sum, root -> val});
        }
        
    public:
        int maxPathSum(TreeNode* root) {  // it is the original function
            int best = INT_MIN;
            int eval = solution(root, best);
            return max(best, eval);
        }
        
    };
  • 相关阅读:
    HDU1698(线段树入门题)
    POJ2528(离散化+线段树区间更新)
    POJ3630(Trie树)
    HDU1251(字典树)
    HDU1247(经典字典树)
    POJ2513(字典树+图的连通性判断)
    POJ1363
    UVa11624(逃离火焰问题)
    HDOJ1495(倒水BFS)
    poj3414Pots(倒水BFS)
  • 原文地址:https://www.cnblogs.com/sherry-yang/p/11421704.html
Copyright © 2011-2022 走看看