在一棵树之中寻找最大和的路径
在刚开始可能会使我们感到迷惑
但是在找到其中的原理,再运用递归
便能够巧妙地将其表示出来!
题目地址:https://leetcode.com/problems/binary-tree-maximum-path-sum/#/description
题目:Binary Tree Maximum Path Sum
描述:
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
.
解答:
class Solution {
public:
int maxToRoot(TreeNode*root, int& re){
if (!root) return 0;
int l = maxToRoot(root->left, re);
int r = maxToRoot(root->right, re);
if (l < 0) l = 0;
if (r < 0) r = 0;
if (l + r + root->val > re) re = l + r + root->val;
return root->val += max(l, r);
}
int maxPathSum(TreeNode* root) {
int max = -2147483648;
maxToRoot(root, max);
return max;
}
};
参考了解法中O(n)的答案,简而言之,便是解析其中原理,总而言之,max刚开始设置为最小负数,防止树中存在着负值,并将地址传到函数之中,在函数遍历每个结点时,现将左子树和右子树中链接其根节点最大路径算出,re值代表着目前为止所遍历的结点中,最大路径的值,就这样层层推进,除去左子树+右子树+根这样特殊的情况,便能得出最大的路径值。