Created
December 29, 2012 13:57
-
-
Save pdu/4407089 to your computer and use it in GitHub Desktop.
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. http://www.leetcode.com/onlinejudge
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 <algorithm> | |
| using namespace std; | |
| /** | |
| * Definition for binary tree | |
| * struct TreeNode { | |
| * int val; | |
| * TreeNode *left; | |
| * TreeNode *right; | |
| * TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
| * }; | |
| */ | |
| #define MIN_INT -0x7fffffff | |
| class Solution { | |
| public: | |
| void max_pathsum_(int& ret, int& pathSum, TreeNode* root) { | |
| if (root == NULL) { | |
| ret = MIN_INT; | |
| pathSum = 0; | |
| return; | |
| } | |
| int left_ret; | |
| int left_pathSum; | |
| int right_ret; | |
| int right_pathSum; | |
| max_pathsum_(left_ret, left_pathSum, root->left); | |
| max_pathsum_(right_ret, right_pathSum, root->right); | |
| pathSum = max(max(left_pathSum, right_pathSum) + root->val, 0); | |
| ret = max(max(left_ret, right_ret), left_pathSum + right_pathSum + root->val); | |
| } | |
| int maxPathSum(TreeNode *root) { | |
| int ret = 0; | |
| int pathSum = 0; | |
| max_pathsum_(ret, pathSum, root); | |
| return ret; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment