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 does not need to go through the root.
For example:
Given the below binary tree,
1
/ \
2 3
return 6
算法
求一棵二叉树上的最大路径。
直接 DFS 就可以了,返回以这一棵子树且一端在上的最大路径,然后维护一个最大路径就行了。
class Solution {
private:
int ret;
int dfs(TreeNode *root) {
if (root == NULL)
return 0;
int left_sum = max(0, dfs(root->left));
int right_sum = max(0, dfs(root->right));
ret = max(ret, left_sum + right_sum + root->val);
return max(left_sum, right_sum) + root->val;
}
public:
int maxPathSum(TreeNode *root) {
ret = INT_MIN;
dfs(root);
return ret;
}
};