首页 > 代码库 > [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
Return 6.

思路:

用一个全局变量来记录最大路径和。

对于一个结点,一旦得到他的左子树与右子树的最大路径和,那么也就能得到最终该结点的最大路径和。

递归函数很好理解。如下:

int maxToRoot(TreeNode* root,int &result)
    {
        if (root == NULL)return 0;
        int left = maxToRoot(root->left,result);
        int right = maxToRoot(root->right, result);
        if (left  < 0)left = 0;
        if (right < 0)right = 0;
        if (left + right + root->val > result) result = left + right + root->val;
        return root->val += max(left,right);
    }
    int maxPathSum(TreeNode* root)
    {
        int max = -2147483648;
        maxToRoot(root, max);
        return max;
    }

参考:

https://discuss.leetcode.com/topic/5508/simple-o-n-algorithm-with-one-traversal-through-the-tree

[leetcode-124-Binary Tree Maximum Path Sum]