Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int maxPathSum(struct Node *root, int &result) {
- if (root == NULL) return 0; // Base case
- // Find maximum sum in left and right subtree. Also find
- // maximum root to leaf sums in left and right subtrees
- // and store them in lLPSum and rLPSum
- int lcost = maxPathSum(root->left, res);
- int rcost = maxPathSum(root->right, res); //Step 1
- // Find the maximum path sum passing through root
- int curr_sum = lcost + rcost + root->data;
- // Update res (or result) only when needed
- if (result < curr_sum && (root->left && root->right)) {
- result = curr_sum;// step 2
- }
- // Return the maximum (root to leaf path) cost
- if (root->left == NULL) {// step 3
- return root->value + rcost;
- } else if (root->right == NULL) {
- return root->value + lcost;
- }
- return max(lcost, rcost) + root->data;
- }
- // The main function which returns sum of the maximum
- // sum path between two leaves. This function mainly uses
- // maxPathSum()
- int FindMaxPathCost(Node *root) {
- int result = 0;
- maxPathSum(root, result);
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment