Binary Tree Maximum Path Sum

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.

Example

Example 1:

Input: [1,2,3]

       1
      / \
     2   3

Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

Note

使用ResultType:

直接比较:

定义全局变量res,并求左右子树的最大值

结果为max(res, root.val, left + root.val + right, left + root.val, right + root.val)

分治left和right,对于helper函数,返回值是max(root.val, root.val + left, root.val + right),维护结果值res:

  • left为负数:最大值是max(res, root.val, root.val + right)

  • right为负数:最大值是max(res, root.val, root.val + left)

  • 都不为负:最大值是max(res, root.val + left + right)

最大和路径有这么几种可能:

  • 从 root 出发,路上看到负数,不采用;

  • 从 root 出发,路上看到负数,负数后面存在总和超过负数节点的路径;

  • 最大和在某个从 leaf node 往上走的一条路径上,不过 root.

  • 左路径最大,采用左路径;

  • 右路径最大,采用右路径;

  • 单独节点最大,可能是 左/右/根 其中之一。

换句话说,一个重要的问题是,我们只能从 root 开始,也没有 parent 指针,但是最优的路径可能却和 root 是不连续的,这就切断了 Binary Tree divide & conquer / Tree DFS 里面大多数做法中非常依赖的性质,即层层递归之前 左/右 子树和根节点的联系。

Code

Last updated