Created
December 10, 2018 13:10
-
-
Save fpdjsns/e72d37665a51768f00647d46f414ef0c to your computer and use it in GitHub Desktop.
[leetcode] 124. Binary Tree Maximum Path Sum : https://leetcode.com/problems/binary-tree-maximum-path-sum/
This file contains 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
/** | |
* Definition for a binary tree node. | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
int ans = 0; | |
int maxNum = 0; | |
int getAns(TreeNode* root){ | |
if(root == NULL) return 0; | |
int now = root->val; | |
maxNum = max(maxNum, now); | |
int left = getAns(root->left); | |
int right = getAns(root->right); | |
int sum = max(now, now + left); | |
sum = max(sum, now + right); | |
ans = max(ans, sum); | |
ans = max(ans, now + right + left); | |
return max(sum, 0); | |
} | |
int maxPathSum(TreeNode* root) { | |
ans = root->val; | |
maxNum = root->val; | |
getAns(root); | |
return maxNum >= 0 ? ans : maxNum; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment