Leetcode 124. Binary Tree Maximum Path Sum

Leetcode 124. Binary Tree Maximum Path Sum

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

For example:
Given the below binary tree,

       1
      / \
     2   3

Solution #1 Recursive Traversal

Time: O ( n )
Space: O ( n )

一个漂亮的递归就可以解决这个问题。dfs的返回值表示了以当前节点为端点的路径所能拥有的最大值。该值由max(root->val + left, root->val + right)可求得。

包含当前节点的路径所能达到的最大值由root->val + left + right确定。这个公式和返回值公式的区别在于返回值的公式中,当前节点不能作为中间节点。

另外,很重要的一点就是,leftright的值会被置为0,如果他们本身的值小于0的话,意味着小于0的节点不会被添加到路径中。

Note: Both left and right will be set to 0 if their value is less than 0. The intuition behind this is that we do NOT consider a node whose maximum path sum is less than 0.

An elegant recursion could solve this problem. The return value of dfs indicates the maximum path sum where the current node is the start point of this path. Therefore, it only contains two cases: 1) root->val + left and root->val + right.

In order to calculate the maximum path sum, we can applied the formula

max_sum = max(max_sum, root->val + left + right)

where root->val + left + right can calculate the maximum path sum at current node (current node does NOT have to be the end point of a path, which means it could be a intermediate node).

class Solution {
public:
    int maxPathSum(TreeNode* root) {
        int max_sum = root->val;
        dfs(root, max_sum);
        return max_sum;
    }

    int dfs(TreeNode *root, int &max_sum) {
        if( !root )
            return 0;

        int left = max(0, dfs(root->left, max_sum));
        int right = max(0, dfs(root->right, max_sum));

        max_sum = max(max_sum, root->val + left + right);

        return max(root->val + left, root->val + right);
    }
};

猜你喜欢

转载自blog.csdn.net/zzy_zhangzeyu_/article/details/79696689