sweet1cris

Untitled

Oct 18th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1.  int maxPathSum(struct Node *root, int &result) {
  2.     if (root == NULL) return 0;  // Base case
  3.     // Find maximum sum in left and right subtree. Also find
  4.     // maximum root to leaf sums in left and right subtrees
  5.     // and store them in lLPSum and rLPSum
  6.     int lcost = maxPathSum(root->left, res);
  7.     int rcost = maxPathSum(root->right, res); //Step 1
  8.  
  9.     // Find the maximum path sum passing through root
  10.     int curr_sum = lcost + rcost + root->data;
  11.  
  12.     // Update res (or result) only when needed
  13.     if (result < curr_sum && (root->left && root->right)) {
  14.         result = curr_sum;// step 2
  15.     }
  16.  
  17.  
  18.     // Return the maximum (root to leaf path) cost
  19.     if (root->left == NULL) {// step 3
  20.         return root->value + rcost;
  21.     } else if (root->right == NULL) {
  22.         return root->value + lcost;
  23.     }
  24.     return max(lcost, rcost) + root->data;
  25.  }
  26.  
  27. // The main function which returns sum of the maximum
  28. // sum path between two leaves.  This function mainly uses
  29. // maxPathSum()
  30.  int FindMaxPathCost(Node *root) {
  31.     int result = 0;
  32.     maxPathSum(root, result);
  33.     return result;
  34.  }
Advertisement
Add Comment
Please, Sign In to add comment