树的动态规划,路径不可以在相邻层。
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int res[100000]={0};
int dp[100000] = {0};
int MaxValue = -1;
int rob(TreeNode* root) {
if(root==NULL)
return 0;
int x=0;
x = dfs(root);
int sum = 0;
vector<int> resSum;
for (int i = 0; i <x ; ++i) {
if(res[i]==-1){
resSum.push_back(sum);
sum = 0;
}
else{
sum += res[i];
}
}
dp[0] = resSum[0];
if(resSum.size()==1)
return dp[0];
dp[1] = max(resSum[1], dp[0]);
if(resSum.size() == 2) {
return dp[1];
}
MaxValue = dp[1];
for (int j = 2; j < resSum.size(); j++) {
dp[j] = max(resSum[j]+dp[j-2],dp[j-1]);
MaxValue = max(MaxValue,dp[j]);
}
return MaxValue;
}
int dfs(TreeNode* root){
queue<TreeNode *> q;
TreeNode* tmp;
q.push(root);
q.push(NULL);
int i = 0;
if(root == NULL)
return 0;
for( i =0 ;q.empty()!=1;i++){
tmp = q.front();
q.pop();
if(tmp!=NULL) {
res[i] = tmp->val;
if (tmp->left != NULL)
q.push(tmp->left);
if (tmp->right != NULL)
q.push(tmp->right);
}
else{
if(q.empty()==1)
break;
q.push(NULL);
res[i] = -1;
}
}
res[i] = -1;
return i+1;
}
};
int main() {
TreeNode *root = new TreeNode(2);
TreeNode *lroot = new TreeNode(1);
TreeNode *rroot = new TreeNode(3);
root->left = lroot;
root -> right = rroot;
TreeNode *root2 = new TreeNode(4);
TreeNode *root3 = new TreeNode(3);
TreeNode *root4 = new TreeNode(1);
// lroot ->left = root2;
lroot ->right = root2;
// rroot ->right = root4;
Solution s;
int x=0;
x = s.dfs(root);
int sum = 0;
vector<int> resSum;
for (int i = 0; i <x ; ++i) {
if(s.res[i]==-1){
resSum.push_back(sum);
sum = 0;
}
else{
sum += s.res[i];
}
}
cout<<s.rob(root);
return 0;
}