简体   繁体   English

树的路径中的最大总和是多少

[英]what is the max sum in path of tree

https://practice.geeksforgeeks.org/problems/maximum-path-sum/1 this is question from geeks for geeks. https://practice.geeksforgeeks.org/problems/maximum-path-sum/1这是来自极客的问题。 i wrote my ans.我写了我的答案。 but it is giving wrong.但这是错误的。 what is problem with my logic?我的逻辑有什么问题?

int path(Node *root, int & max_sum)
{
  if(root==NULL)
    return 0;
  int l=path(root->left,max_sum);
  int r=path(root->right,max_sum);
  max_sum=max(max_sum,l+r+root->data);
  return max(l,r)+root->data;
}

int maxPathSum(Node *root) 
{
  int max_sum=INT_MIN;
  path(root,max_sum);
  return max_sum;
  // code here
}

The problem statement says问题陈述说

Find the maximum possible sum from one leaf node to another.找到从一个叶节点到另一个叶节点的最大可能总和。

So, when you do所以,当你这样做

 max_sum=max(max_sum,l+r+root->data);

You will need to check whether the root has both the children.您将需要检查root是否有两个孩子。 Otherwise, they won't be considered in the final answer .否则,它们将不会被考虑在最终答案中。

You also did你也做过

if(root==NULL)  return 0;

and

max(l,r)+root->data;

These both combined are overriding a single leaf node child whose value is negative since 0 is greater than any negative integer.这两个组合都覆盖了单个叶子节点子节点,其值为负数,因为 0 大于任何负数 integer。

So overall your code should look like this:所以总的来说你的代码应该是这样的:

int path(Node *root, int & max_sum)
{
  if(root==NULL) return 0;
  int l=path(root->left,max_sum);
  int r=path(root->right,max_sum);
  if(root->left != NULL && root->right != NULL){
      max_sum = max(max_sum,l + r + root->data);
  }

  if(root->left != NULL && root->right == NULL) return  l + root->data;
  if(root->right != NULL && root->left == NULL) return  r + root->data;
  return max(l,r) + root->data;
}

int maxPathSum(Node *root) 
{
  int max_sum=INT_MIN;
  path(root,max_sum);
  return max_sum;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM