LeetCode 124. Binary Tree Maximum Path Sum

来源:互联网 发布:吉林省卫生网络直报 编辑:程序博客网 时间:2024/05/27 06:56

题目

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.


思路

这个问题是求二叉树的最大路径和。二叉树的问题可以用递归来解决,用深度优先算法来解决这个最大路径和。
对于任意一个节点root,最大路径有可能是四种情况:
1) root
2) 左子树路径+root
3) root+右子树路径
4) 左子树路径+root+右子树路径

递归来求左右子树的最大路径和,如果求得的左、右子树的值大于0,就加到这个和上,但是要注意左右子树不能单独存在,必须是有root这个结点连接的。


代码

/** * 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 {private:    int max_sum;public:    int maxPathSum(TreeNode* root) {        if(root == NULL)            return 0;            max_sum = INT_MIN;        dfs(root);        return max_sum;    }    int dfs(TreeNode* root)    {        if(root == NULL)            return 0;        int l = dfs(root->left);        int r = dfs(root->right);        int sum = root->val;         if(l>0)            sum += l;        if(r>0)            sum += r;        max_sum = max(max_sum,sum);        return root->val + max(0,max(l,r));    }};
0 0