-
-
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; | |
| }; | |
| 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