938.
class Solution {
public:
int ans;
int rangeSumBST(TreeNode* root, int low, int high) {
dfs(root, low, high);
return ans;
}
void dfs(TreeNode* root, int low, int high){
if(root==nullptr) return;
dfs(root->left, low, high);
if(root->val >= low && root->val <= high){
ans += root->val;
}
dfs(root->right, low, high);
}
};
//法二
class Solution {
public:
int rangeSumBST(TreeNode* root, int low, int high) {
if(root == nullptr) return 0;
if(root->val > high){
return rangeSumBST(root->left, low, high);
}else if(root->val < low){
return rangeSumBST(root->right, low, high);
}else{
return root->val + rangeSumBST(root->right, low, high)+rangeSumBST(root->left, low, high);
}
}
};
894.
- ??没太看懂??
- 左边出那么多种情况,右边也是?
class Solution {
public:
vector<TreeNode*> allPossibleFBT(int n) {
vector<TreeNode*> ans;
if(n==1){
TreeNode* root = new TreeNode(0);
ans.push_back(root);
}else{
for(int i = 1; i<= n-2; i+= 2){
for(auto left: allPossibleFBT(i)){
for(auto right: allPossibleFBT(n-i-1)){
TreeNode* root= new TreeNode(0);
root->left = left;
root->right = right;
ans.push_back(root);
}
}
}
}
return ans;
}
};
783.
class Solution {
public:
int ans = INT_MAX;
TreeNode* prev;
int minDiffInBST(TreeNode* root) {
dfs(root);
return ans;
}
void dfs(TreeNode* root){ //
if(root == nullptr) return;
dfs(root->left);
if(prev != nullptr) ans = min(ans, root->val-prev->val);
prev = root;
dfs(root->right);
}
};