Problem :
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.
Example:
Given the below binary tree,
1
/ \
2 3
Return 6.
Algorithm:
本题的意思为在一棵二叉树中寻找一条结点和最大的路径(不需要经过根节点)。这道题可采用递归的做法。
算法思路为,对于每一个给定结点,递归得到其左子树的最大值和右子树的最大值(注意,如果最大值的和小于0,则取最大值为0,表示不加入该条路径),再将其值与其左右子树的最大值相加,即可得到经过该结点的最大路径和。遍历完所有的结点,不断更新当前最大路径和,便可得到整棵树的最大路径和。由于每个结点只访问一次,因此该算法的时间复杂度为O(n)。
Code:
/**
* 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 dfs(TreeNode* root) {
if(!root) return 0;
int lmax = dfs(root -> left);
int rmax = dfs(root -> right);
if(lmax < 0) lmax = 0;
if(rmax < 0) rmax = 0;
if(maxn < lmax + rmax + root -> val)
maxn = lmax + rmax + root -> val;
return max(lmax, rmax) + root -> val;
}
int maxPathSum(TreeNode* root) {
if(!root) return 0;
maxn = root -> val;
dfs(root);
return maxn;
}
int maxn;
};