Binary Tree Maximum Path Sum
Description
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
Example Given the below binary tree: 1 / \ 2 3 return 6.
Link
Method
- x
- x
Example
- 1
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: The root of binary tree. * @return: An integer */ int maxPathSum(TreeNode *root) { // write your code here if (!root) { return 0; } pair<int, int> result = helper(root); return result.second; } private: // <int,int> root2any , any2any // pair<int, int> pernode; pair<int, int> helper(TreeNode* root){ if (!root) { return make_pair(INT_MIN, INT_MIN); } pair<int, int> left = helper(root->left); pair<int, int> right = helper(root->right); // update two kinds of path // root will be every recursion's root int root2any = max(0, max(left.first, right.first)) + root->val; int any2any = max(left.second, right.second); // find max any to any // max any to any, left any to its root + right any to its root + root any2any = max(any2any, max(0, left.first) + max(0, right.first) + root->val); return make_pair(root2any, any2any); } };
Similar problems
x
Tags
x