代码语言:javascript复制
/**
* 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 maxValue(TreeNode* root, int k) {
vector<int> ans=dfs(root,k);
return *max_element(ans.begin(),ans.end());
}
vector<int> dfs(TreeNode* root,int k){
if(!root)return vector<int>(k 1);
vector<int>l=dfs(root->left,k);
vector<int>r=dfs(root->right,k);
vector<int>ans(k 1,0);
for(int i=0;i<=k;i ){
for(int j=0;j<=k;j ){
ans[0]=max(ans[0],l[i] r[j]);
if(i j 1<=k)ans[i j 1]=max(ans[i j 1],l[i] r[j] (root->val));
}
}
return ans;
}
};