Skip to content

124. Binary Tree Maximum Path Sum

难度:Hard

刷题内容

原题连接

  • https://leetcode.com/problems/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

˼· **- ʱ�临�Ӷ�: O(N)*- �ռ临�Ӷ�: O(1)***

�����뵽内容描述DP��ʱ�临�Ӷ�ΪO(n^2)内容描述���Ƕ�������ֻ内容描述内容描述����ˣ����ǿ����ø��Ż����㷨�������ú内容描述������Ȼ���¼������ڵ�����·���� ans�Ƚϡ����� max(l,r) 内容描述ڵ��ֵ��

/**
 * 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 ans = INT_MIN;
    int travel(TreeNode* root)
    {
        if(!root)
            return 0;
        int l = travel(root ->left);
        int r = travel(root ->right);
        if(l < 0)
            l = 0;
        if(r < 0)
            r = 0;
        int temp = r + l + root ->val;
        ans = max(ans,temp);
        return max(l,r) + root ->val;
    }
    int maxPathSum(TreeNode* root) {
        travel(root);
        if(ans == INT_MIN)
            return 0;
        return ans;
    }
};


回到顶部