标签:
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
求树的一点到另一点的最大路径,利用递归的方法,ans 在 左子树,右子树,root+左+右的最大中产生。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int ans; int maxPathSum(TreeNode *root) { ans = INT_MIN; travel(root); return ans; } int travel(TreeNode * root){ if(root == NULL) return 0; int sum = root->val; int leftsum = travel(root->left); int rightsum = travel(root->right); if(leftsum > 0) sum += leftsum; if(rightsum > 0) sum += rightsum; ans = max(ans,sum); sum = max(leftsum,rightsum); return root->val + (sum > 0 ? sum : 0); } };
标签:
原文地址:http://blog.csdn.net/sina012345/article/details/43200851