124. Binary Tree Maximum Path Sum [JavaScript]

一、题目

  Given a non-empty binary tree, find the maximum path sum.

  For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

二、题目大意

  给定一个非空的二叉树,找到最大路径和。对于这个问题,路径被定义为沿着父子连接从某个起始节点到树中任意节点的任意节点序列。路径必须至少包含一个节点,并且不需要通过根目录。

三、解题思路

  一个二叉树中存在的路径有以下几种情况:

    1
   / \
  2   3

  对于上述二叉树的路径有:

  1, 2, 3, 1->2, 1->3, 2->1->3

  那么在递归二叉树的过程中,记录每个子树的最大路径即可。

四、代码实现
const maxPathSum = root => {

  let ans = Number.MIN_SAFE_INTEGER
  maxTreeSum(root)

  return ans
  function maxTreeSum (root) {
    if (!root) {
      return Number.MIN_SAFE_INTEGER
    }
    const rootValue = root.val
    const left = maxTreeSum(root.left)
    const right = maxTreeSum(root.right)
    const currentTreeSum = Math.max.call(this, rootValue, rootValue + left, rootValue + right)
    ans = Math.max.call(this, ans, currentTreeSum, left, right, rootValue + left + right)
    return currentTreeSum
  }
}

  如果本文对您有帮助,欢迎关注微信公众号,为您推送更多内容,ε=ε=ε=┏(゜ロ゜;)┛。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值