Skip to content

Latest commit

 

History

History
78 lines (62 loc) · 1.59 KB

0124._Binary_Tree_Maximum_Path_Sum.md

File metadata and controls

78 lines (62 loc) · 1.59 KB

124. Binary Tree Maximum Path Sum

难度:Hard

刷题内容

原题连接

内容描述

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;
    }
};