题意:

image.png

解题思路:

  1. 思路:
  2. 1. 递归计算左右子树的最大值,将它与0进行比较,如果大于才加上去,否则就舍去一边;
  3. 2. 按层级与左右子树三个值相加更新全局答案;
  4. 3. 返回左右子树比较大的那个子树的和[根节点+max(left, right)]

PHP代码实现:

  1. class Solution {
  2. public $max = PHP_INT_MIN;
  3. /**
  4. * @param TreeNode $root
  5. * @return Integer
  6. */
  7. function maxPathSum($root) {
  8. if(empty($root)) return 0;
  9. $this->helper($root);
  10. return $this->max;
  11. }
  12. function helper($node) {
  13. if(empty($node)) return 0;
  14. $left = max($this->helper($node->left), 0);
  15. $right = max($this->helper($node->right), 0);
  16. //每一层最大值进行比较
  17. //求的过程中考虑包含当前根节点的最大路径
  18. $this->max = max($this->max, $node->val + $left + $right);
  19. //只返回包含当前根节点和左子树或者右子树的路径
  20. return $node->val + max($left, $right);
  21. }
  22. }

GO代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func maxInt(a, b int) int {
  10. if a > b {
  11. return a
  12. } else {
  13. return b
  14. }
  15. }
  16. func maxPathSum(root *TreeNode) int {
  17. maxResult := math.MinInt32
  18. var pathSum func(*TreeNode) int
  19. pathSum = func(curNode *TreeNode) int {
  20. if curNode == nil {
  21. return 0
  22. }
  23. left := maxInt(0, pathSum(curNode.Left))
  24. right := maxInt(0, pathSum(curNode.Right))
  25. maxResult = maxInt(maxResult, left + curNode.Val + right)
  26. return curNode.Val + maxInt(left, right)
  27. }
  28. _ = pathSum(root)
  29. return maxResult
  30. }