LeetCode: Binary Tree Maximum Path Sum
LeetCode: Binary Tree Maximum Path Sum Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example: Given the below binary tree, 1 / \ 2 3 Return 6 . 地址: https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/ 算法:用递归来解决。首先,最大的路径和出现在以下三种情况:1)出现在左子树中;2)出现在右子树;3)经过根节点,在这种情况下,相当与左边从根节点到叶节点的最大路径加上右边从根节点到叶节点的最大路径。 对于第三种情况也可以用递归来解决。代码: 1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11