Binary Tree Maximum Path Sum (LeetCode)
Question:
https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/
解答:
这问题求的是任何一个节点它的左边最大Path和右边最大Path的和的最大值。对于任意一个node来说,它的最大Path Sum无非是以下几种情况中的一种:
1. node左子树中的最大Path Sum
2. node右子树中的最大Path Sum
3. 左子树到node的最大Path(max(max path of node->left + node, node))和右子树到node的最大Path(max(max path of node->right + node, node))
所以递归函数不仅要返回最大Path Sum,也要返回当前这个node所能形成的最大Path。
注意左右子树不存在的情况,以及Path Sum可能是负数的情况。
int maxPathSum(TreeNode *root) { if (!root) return 0; int maxPath = 0; int maxSum = 0; FindMaxPathSum(root, maxPath, maxSum); return maxSum; } void FindMaxPathSum(TreeNode* root, int& maxPath, int& maxSum) { maxSum = root->val; int leftMaxPath = 0; int rightMaxPath = 0; int childMaxSum = 0; if (root->left) { FindMaxPathSum(root->left, leftMaxPath, childMaxSum); maxSum = max(childMaxSum, maxSum); } if (root->right) { FindMaxPathSum(root->right, rightMaxPath, childMaxSum); maxSum = max(maxSum, childMaxSum); } maxPath = root->val; if (max(leftMaxPath, rightMaxPath) > 0) maxPath += max(leftMaxPath, rightMaxPath); int thisSum = root->val + (leftMaxPath > 0 ? leftMaxPath : 0) + (rightMaxPath > 0 ? rightMaxPath : 0); maxSum = max(maxSum, thisSum); }
之前以为是求任何一棵子树的所有点的和的最大值,不过方法一样 (未验证)。
// 最大子树的和,可能包含负数,子树的叶节点可能是任意节点(不一定是原来的叶节点),如果都是非负数,则是所有节点的和。 void FindMaxSubTreeSum(TreeNode* root, int& maxSumWithRoot, int& maxSum) { maxSumWithRoot = root->val; maxSum = root->val; int childMaxSumWithRoot = 0; int childMaxSum = 0; if (root->left) { FindMaxPathSum(root->left, childMaxSumWithRoot, childMaxSum); maxSumWithRoot = max(maxSumWithRoot, childMaxSumWithRoot + maxSumWithRoot); maxSum = max(childMaxSum, maxSumWithRoot); } if (root->right) { FindMaxPathSum(root->right, childMaxSumWithRoot, childMaxSum); maxSumWithRoot = max(maxSumWithRoot, childMaxSumWithRoot + maxSumWithRoot); maxSum = max(childMaxSum, maxSumWithRoot); } }