/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ #include <functional> class Solution { public: /** * * @param root TreeNode类 * @return int整型 */ int maxPathSum(TreeNode* root) { int res = INT_MIN; function<int(TreeNode *)> dfs = [&](TreeNode *root) -> int { if (!root) { return INT_MIN; } auto l = dfs(root->left); auto r = dfs(root->right); res = max(res, root->val + max(l, 0) + max(r, 0)); return max({root->val, root->val + l, root->val + r}); }; dfs(root); return res; } };
思路:dfs。
全局变量res保存最大路径,返回值代表从当前结点出发能得到的最大路径。