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 | Example 1: |
对于每条路径,都有一个最高节点,每个节点都可以看作一个最高节点,所有最高节点中的最大值即为所求。因此可以递归求解,对于每个最高节点,路径肯定包含其节点的值,左或右子树的最大路径不能为负,否则取0,分别左右子树的最大路径和最高节点的值累加,即为以最高节点为根的最大路径和,更新maxSum;另外对于每个最高节点,只能返回路径值较大一侧的子树给上一层,否则不符题意。
1 | /** |