Leetcode: Binary Tree maximum path sum
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / 2 3
Return6.
Address: https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/
Algorithm: recursive. First, the maximum path appears in the following three situations: 1) appear in the left subtree; 2) appear in the right subtree; 3) pass through the root node. In this case, it is equivalent to the maximum path from the root node to the leaf node on the left plus the maximum path from the root node to the leaf node on the right.
The third case can also be solved using recursion. Code:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */10 class Solution {11 public:12 int maxPathSum(TreeNode *root) {13 if(!root){14 return INVALID;15 }16 int left = maxPathSum(root->left);17 int right = maxPathSum(root->right);18 int mid = root->val;19 int mid_left =maxLoadSum(root->left);20 if(mid_left > 0){21 mid += mid_left;22 }23 int mid_right = maxLoadSum(root->right);24 if(mid_right > 0){25 mid += mid_right;26 }27 if(left != INVALID && left > mid){28 mid = left;29 }30 if(right != INVALID && right > mid){31 mid = right;32 }33 return mid;34 }35 int maxLoadSum(TreeNode *root){36 if(flag.find(root) != flag.end()){37 return flag[root];38 }39 if(!root){40 flag[root] = -1;41 return -1;42 }43 int sum = root->val;44 int left = maxLoadSum(root->left);45 int right = maxLoadSum(root->right);46 if (left > right){47 right = left;48 }49 if(right > 0){50 sum += right;51 }52 flag[root] = sum;53 return sum;54 }55 static const int INVALID = 0x7FFFFFFF;56 map<TreeNode *,int> flag;57 };
Leetcode: Binary Tree maximum path sum