669. 修剪二叉搜索树
思路
代码
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root == nullptr) return nullptr;
if(root->val < low) {
TreeNode* right = trimBST(root->right,low,high);
return right;
}
if(root->val > high) {
TreeNode* left = trimBST(root->left,low,high);
return left;
}
root->left = trimBST(root->left,low,high);
root->right = trimBST(root->right,low,high);
return root;
}
};
总结
- 关于接住下一层节点的部分有点绕
108.将有序数组转换为二叉搜索树
思路
代码
class Solution {
public:
TreeNode* travelsal(vector<int>& nums, int left, int right) {
if(left > right) return nullptr;
int mid = left + (right - left) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = travelsal(nums,left,mid-1);
root->right = travelsal(nums,mid+1,right);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root = travelsal(nums,0,nums.size()-1);
return root;
}
};
总结
538.把二叉搜索树转换为累加树
思路
代码
class Solution {
public:
int pre = 0;
void travelsal(TreeNode* cur) {
if(cur == nullptr) return;
travelsal(cur->right);
cur->val += pre;
pre = cur->val;
travelsal(cur->left);
}
TreeNode* convertBST(TreeNode* root) {
pre = 0;
travelsal(root);
return root;
}
};
总结