Given a binary tree, find the maximum pathsum.
The path may start and end at any node inthe tree.
For example:
Given the below binary tree,
Return 6 .
分析一:
刚开始想到的方法是:参照求解最大连续子数组和的方式,用递归求解。取得最大和的path有三种情况。
1、 该路径不包含root,并只在左子树中;
2、 该路径不包含root,并只在右子树中;
3、 该路径包含root;
然后递归求解三种情况,取三者的最大值。
但是这种思路的时间复杂度太高。
代码如下:
/**
* Definition for binary tree
* 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 = FindMaxPath(root);
return maxsum;
}
private:
int FindMaxPath(TreeNode *root) {
int cmax = INT_MIN;
int leftmax = INT_MIN, rightmax = INT_MIN, acrossmax = INT_MIN;
if (root == NULL)
return cmax;
if (root->left == NULL && root->right == NULL)
return root->val;
if (root->left)
leftmax = FindMaxPath(root->left);
if (root->right)
rightmax = FindMaxPath(root->right);
cmax = max(leftmax, rightmax);
acrossmax = FindMaxSubPathAcrossRoot(root);
cmax = max(cmax, acrossmax);
return cmax;
}
int FindMaxSubPath(TreeNode *root) {
int maxleft = (-1*inf);
int maxright = (-1*inf);
if (root->left == NULL && root->right == NULL)
return root->val;
if (root->left)
maxleft = FindMaxSubPath(root->left);
if (root->right)
maxright = FindMaxSubPath(root->right);
return max(maxleft, maxright) + root->val;
}
int FindMaxSubPathAcrossRoot(TreeNode *root){
int maxleft = (-1*inf), maxright = (-1*inf), maxroot = root->val;
if (root->left)
maxleft = FindMaxSubPath(root->left);
if (root->right)
maxright = FindMaxSubPath(root->right);
if (maxleft > 0)
maxroot += maxleft;
if (maxright > 0)
maxroot += maxright;
return maxroot;
}
};
分析二:
自底向上。采用DFS来遍历BinaryTree。在每一层节点都先遍历左子树,判断左子树的最长路径是否是当前最长路径,代码表示为max_path = max(max_path, sum),然后返回左子树的单边最长路径L,代码表示为return (L <= 0 && R <= 0) ? root->val : root->val + max(L, R),再遍历右子树,判断右子树的最长路径是否是当前最长路径,然后返回右子树的单边最长路径R,结合左右子树的最长单边路径,计算该层子树的最大长路径,判断该路径是否是当前最长路径,并向上层返回以该层根节点为起点的单边最长路径。
代码如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode *root) {
DFS(root);
return max_path;
}
private:
int DFS(TreeNode *root) {
if (root == nullptr)
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_path = max(max_path, sum);
return (L <= 0 && R <= 0) ? root->val : root->val + max(L, R);
}
int max_path = INT_MIN;
};