leetcode---binary-tree-maximum-path-sum---树

来源:互联网 发布:plsql输入ip连接数据 编辑:程序博客网 时间:2024/05/29 17:05

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

Return6.

/** * 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 ans;    int dfs(TreeNode *root)    {        if(!root)            return 0;        int lmax = dfs(root->left);        int rmax = dfs(root->right);        int v = max(root->val, max(root->val+lmax, root->val+rmax));        int v1 = max(v, root->val+lmax+rmax);        if(v1 > ans)            ans = v1;        return v;    }    int maxPathSum(TreeNode *root)     {        ans = INT_MIN;        dfs(root);        return ans;    }};