Binary Tree Maximum Path Sum

来源:互联网 发布:如何下载windows 10 编辑:程序博客网 时间:2024/06/06 09:33
/** * 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 maxPathSum(TreeNode* root)     {        int res = INT_MIN;        dfs(root,res);        return res;    }    int dfs(TreeNode* root,int & res)    {        if (!root)            return 0;        int left = dfs(root->left,res);        int right = dfs(root->right,res);        int cur = root->val + (left > 0 ? left : 0) + (right > 0 ? right : 0);        res = max(res,cur);        return root->val + max(max(left,right),0);    }};
参考了 http://blog.csdn.net/linhuanmars/article/details/22969069
0 0
原创粉丝点击