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.
此题的path定义具有迷惑性,所以一开始可能写错,只能得到部分用例,具体解释可参见
https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/39811/What-is-the-meaning-of-path-in-this-problem
method 1
要得到树中从一个结点到另一个结点的最大路径和,根据总结的一般规律,可归结为对树的后序遍历。因为对一颗树,要先得到其左子树和右子树的路径和,才能决定到底是取哪一边,因此后序遍历符合要求。
边遍历,边求最大值,最后完成本棵树的路径求和时,要将最大路径和返回给父结点,最大路径和有三种情况:左子树路径+根节点,右子树路径+根节点,根节点
int postOrder(TreeNode* root, int& maxSum){
if (!root) return 0;
int left = postOrder(root->left, maxSum);
int right = postOrder(root->right, maxSum);
int val = root->val;
int curSum = max(val, max(left + val, max(right + val, left + right + val)));
maxSum = max(curSum, maxSum);
return max(val, max(left+val, right + val));
}
int maxPathSum(TreeNode* root) {
if(!root) return 0;
int maxSum = root->val;
postOrder(root, maxSum);
return maxSum;
}
summary
- 树的问题归纳为遍历顺序的问题