標籤:
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;};
124. Binary Tree Maximum Path Sum (Tree; DFS)