Given a 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.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
这种题目和我们以前做的求从头结点到达二叉树的最下面一层节点的路径求和差不多,只不过现在求在这颗树里面任意的路径最大值.
我们先建立求和的思路
树里面的一条路径是什么呢?
从root节点向两边延伸,每次蔓延到的节点,又有两种选择,左,右,在蔓延的过程中一直记录着cur节点+两边蔓延路径的最大值,
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {