Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
For example:
Given the below binary tree,
1 / 2 3
Return 6
.
思路:存在val小于零的情况,所以path不一定是从叶子节点到叶子节点;
/** * 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 maxPathSum(TreeNode *root) { maxSum = INT_MIN; calRootSum(root); return maxSum; } int calRootSum(TreeNode *root) { int leftSum = 0; int rightSum = 0; int sum; if(root->left) { leftSum = calRootSum(root->left); //traverse left subtree } if(root->right) { rightSum = calRootSum(root->right);//traverse right subtree } //val小于零的情况 if(leftSum < 0) { leftSum = 0; } if(rightSum < 0) { rightSum = 0; } sum = root->val+leftSum+rightSum; if(sum > maxSum) { maxSum = sum; } sum = root->val+max(leftSum,rightSum); return sum; } private: int maxSum; };
时间: 2024-10-12 00:14:18