LeetCode-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.

Note:

  • The solution set must not contain duplicate quadruplets.

例子:

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

问题解析:

给二叉树,寻找二叉树中从一个节点到任意一个节点的路径和的最大值。

链接:

思路标签

算法:递归DFS

解答:

  • 我们以递归的思想,深度优先,从下到上寻找最大的路径和;
  • 对于每个节点可以与其左右节点相结合,但是当每个根结点作为左(右)子节点返回时,只能选择该根根结点和其左右子节点中的最大的一个。(这样才能称为路径)
/**
 * 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 maxSum = INT_MIN;
        dfsMaxPath(root, maxSum);
        return maxSum;
    }

    int dfsMaxPath(TreeNode* root, int &maxSum){
        if(!root) return 0;
        int l = max(0, dfsMaxPath(root->left, maxSum));
        int r = max(0, dfsMaxPath(root->right, maxSum));
        maxSum = max(maxSum, l+r+root->val);
        return root->val + max(l,r);
    }
};

猜你喜欢

转载自blog.csdn.net/koala_tree/article/details/80109258