Skip to content

Instantly share code, notes, and snippets.

@esyrt
Forked from luangong/maximum_subtree.cc
Created September 18, 2012 05:26
Show Gist options
  • Select an option

  • Save esyrt/3741421 to your computer and use it in GitHub Desktop.

Select an option

Save esyrt/3741421 to your computer and use it in GitHub Desktop.
求二叉树的最大子树
#include <iostream>
#include <limits>
using namespace std;
struct Node {
int data;
Node *lchild;
Node *rchild;
};
int maxSubtree(Node *root, int& maxSum, Node *& maxNode)
{
int sum = 0;
if (root == NULL)
return 0;
int leftSum = maxSubtree(root->lchild, maxSum, maxNode);
int rightSum = maxSubtree(root->rchild, maxSum, maxNode);
sum = root->data + leftSum + rightSum;
if (sum >= maxSum) {
maxSum = sum;
maxNode = root;
}
return sum;
}
int main()
{
int maxSum = numeric_limits<int>::min();
Node *maxNode;
Node q = { -4, NULL, NULL };
Node r = { 5, NULL, NULL };
Node p = { 3, &q, &r };
int result = maxSubtree(&p, maxSum, maxNode);
cout << maxSum << ", " << maxNode << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment