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
  • Save esyrt/3741421 to your computer and use it in GitHub Desktop.
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;
};
long maxSubtree(Node *root, long& maxSum, Node *& maxNode)
{
long sum = 0;
if (root == NULL) {
maxNode = root;
return 0;
}
long leftSum = maxSubtree(root->lchild, maxSum, maxNode);
long rightSum = maxSubtree(root->rchild, maxSum, maxNode);
sum = root->data + leftSum + rightSum;
if (sum >= maxSum) {
maxSum = sum;
maxNode = root;
}
return sum;
}
int main()
{
long maxSum = numeric_limits<long>::min();
Node *maxNode;
Node q = { 2000000000, NULL, NULL };
Node r = { 1000000000, NULL, NULL };
Node p = { 2000000000, &q, &r };
long result = maxSubtree(&p, maxSum, maxNode);
if (maxNode == NULL)
cout << "The tree is empty!" << endl;
else
cout << maxSum << ", " << maxNode << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment