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
Return 6
.
找出任意两个节点之间的路径,并且该路径的值之和最大。
PS:关键在于递归函数的返回值,应该返回该节点的任意子节点到该节点父节点之间路径的最大值,即root->l返回的值应该为root->l的任意子节点到root能得到的最大值-root->val。同时在遍历时时刻检查sum与max的大小并更新max的值。
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 res=INT_MIN; 14 dfs(root); 15 return res; 16 } 17 18 int dfs(TreeNode *root){ 19 if(root==NULL){ 20 return 0; 21 } 22 int sum=root->val; 23 24 int l=dfs(root->left); 25 int r=dfs(root->right); 26 if(l>0) sum+=l; 27 if(r>0) sum+=r; 28 res=max(res,sum); 29 int tmp=max(l,r); 30 return tmp>0?tmp+root->val:root->val; 31 } 32 int res; 33 };