Exemplo n.º 1
0
void getTargetLeaf(TreeNode* root, int* sum_ref, int cur_sum, TreeNode** target_leaf_ref){
  if (root == NULL)
    return;
    
  cur_sum = cur_sum + root->data;
  if (root->left == NULL && root->right == NULL){
    if (cur_sum > *sum_ref){
      *sum_ref = cur_sum;
      *target_leaf_ref = root;
    }
  }
  
  getTargetLeaf(root->left, sum_ref, cur_sum, target_leaf_ref);
  getTargetLeaf(root->right, sum_ref, cur_sum, target_leaf_ref);
}
Exemplo n.º 2
0
int maxSumPathFromRoot(TreeNode* root){
  if (root == NULL)
    return 0;
    
  TreeNode* target_leaf;
  int max_sum = INT_MIN;
  
  getTargetLeaf(root, &max_sum, 0, &target_leaf);
  
  printPath(root, target_leaf);
  
  return max_sum;
}
Exemplo n.º 3
0
// This function Sets the target_leaf_ref to refer the leaf node of the maximum 
// path sum.  Also, returns the max_sum using max_sum_ref
void getTargetLeaf (node *node1, int *max_sum_ref, int curr_sum, node **target_leaf_ref)
{
    if (node1 == NULL)
        return;
 
    // Update current sum to hold sum of nodes on path from root to this node
    curr_sum = curr_sum + node1->data;
 
    // If this is a leaf node and path to this node has maximum sum so far,
    // then make this node target_leaf
    if (node1->left == NULL && node1->right == NULL)
    {
        if (curr_sum > *max_sum_ref)
        {
            *max_sum_ref = curr_sum;
            *target_leaf_ref = node1;
        }
    }
 
    // If this is not a leaf node, then recur down to find the target_leaf
    getTargetLeaf (node1->left, max_sum_ref, curr_sum, target_leaf_ref);
    getTargetLeaf (node1->right, max_sum_ref, curr_sum, target_leaf_ref);
}
// Returns the maximum sum and prints the nodes on max sum path
int maxSumPath (struct node *node)
{
    // base case
    if (node == NULL)
        return 0;

    struct node *target_leaf;
    int max_sum = INT_MIN;

    // find the target leaf and maximum sum
    getTargetLeaf (node, &max_sum, 0, &target_leaf);

    // print the path from root to the target leaf
    printPath (node, target_leaf);

    return max_sum;  // return maximum sum
}