Binary Tree Maximum Path Sum

来源:互联网 发布:png软件下载 编辑:程序博客网 时间:2024/06/05 01:07

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1      / \     2   3

Return 6.


DFS递归。

在后序遍历的时候,求每个点的最大路径sum=本事的val+左子树的和(如果大于0)+右子树的和(如果大于0)。

其中求左右子树的最大和 = max(root->val, max(root->val+lmax, root->val+rmax))

int ans;int dfs(TreeNode *root){    if(root == NULL)        return 0;    int sum = root->val;    int lmax = 0, rmax = 0;    if(root->left)        lmax = dfs(root->left);    if(root->right)        rmax = dfs(root->right);    if(lmax > 0)        sum += lmax;    if(rmax > 0)        sum += rmax;    ans = max(ans, sum);    return max(root->val, max(root->val+lmax, root->val+rmax));}int maxPathSum(TreeNode *root){    ans = INT_MIN;    dfs(root);    return ans;}


0 0