-
-
Save esyrt/3741421 to your computer and use it in GitHub Desktop.
求二叉树的最大子树
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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