LeetCode 124: Binary Tree Maximum Path Sum Tree dynamic planning, leetcodebinary
Blog reprint please note address: http://blog.csdn.net/sunliymonkey/article/details/48179427
Description
Address: https://leetcode.com/problems/binary-tree-maximum-path-sum/
A binary tree, each of which is labeled with a value, finds a path to maximize the value and value of all nodes in the path.
Example:
Input
1 / \ 2 3
Output
6
Site trap
None
Code
/** * 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 max_sum; int dfs(TreeNode* x){ if(!x) return 0; int l_sum = dfs(x->left); int r_sum = dfs(x->right); if(l_sum < 0)l_sum = 0; if(r_sum < 0)r_sum = 0; int sum = x->val + l_sum + r_sum; max_sum = max(max_sum, sum); return x->val + max(l_sum, r_sum); } int maxPathSum(TreeNode* root) { max_sum = root? root->val: 0; dfs(root); return max_sum; }};
Ranking
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger. Blog address: http://blog.csdn.net/sunliymonkey