问题描述:
Given a non-empty 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 must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
源码:
树的问题当然离不开递归了。找到以每个点为起点的路径的最大值。时间86%,空间100%。
/**
* 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 result = INT_MIN;
int change(TreeNode* root){
if(!root) return 0;
int L = max(change(root->left), 0);
int R = max(change(root->right), 0);
result = max(result, root->val+L+R);
return root->val+max(L,R);
}
int maxPathSum(TreeNode* root) {
if(!root) return 0;
change(root);
return result;
}
};
有递归自然就有非递归,用一个带make_pair的栈,模拟两个递归的变量可以,但是我们今天只看看后序遍历的方法:
时间和空间都和递归是一样的。
/**
* 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) {
if(!root) return 0;
stack<TreeNode*> st;
int result = INT_MIN;
st.push(root);
TreeNode* pre = NULL;
while(!st.empty()){
TreeNode* tmp = st.top();
if((!tmp->left && !tmp->right) || (pre && (pre==tmp->left || pre==tmp->right))){
st.pop();
pre = tmp;
int L, R;
if(tmp->left) L = max(tmp->left->val, 0);
if(tmp->right) R = max(tmp->right->val, 0);
if(tmp->left && tmp->right){
result = max(result, L + R + tmp->val);
tmp->val += max(L, R);
}
else if(tmp->left){
result = max(result, L + tmp->val);
tmp->val += L;
}
else if(tmp->right){
result = max(result, R + tmp->val);
tmp->val += R;
}
else{
result = max(result, tmp->val);
}
}
else{
if(tmp->right) st.push(tmp->right);
if(tmp->left) st.push(tmp->left);
}
}
return result;
}
};