题目: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.
下面代码的思想及编写参考了网址https://github.com/soulmachine/leetcode#leetcode题解题目
解析:用递归方法,先找出节点 root 左子树的最大路径和,再找出其右子树的最大路径和,然后将该节点值与左右子树的最大路径和相加,与之前计算过的最大路径和进行比较;但是切记当我们返回该节点 root 的最大路径和时,我们只能返回一个方向上的,因为在递归中,只能向父节点返回,不可能存在 L -> root -> R 的路径,只能存在 L -> root 或者 R -> root 路径
代码如下:
// 时间复杂度 O(n),空间复杂度 O(logn) class Solution { public: int maxPathSum(TreeNode* root) { int max_sum = INT_MIN; dfs(root, max_sum); return max_sum; } private: int dfs(const TreeNode* root, int& max_sum) { if(!root) return 0; int l = dfs(root -> left); int r = dfs(root -> right); int sum = root -> val; if (l > 0) sum += l; if (r >0) sum += r; max_sum = max(max_sum, sum); return max(r, l) > 0 ? max(r, l) + root -> val : root -> val; } };