669.修剪二叉搜索树
这题修修改改也是做出来了,虽然是跟录里的解法一致,但代码还是写复杂了。
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr) return root;
if (root->val > high || root->val < low) {
if (root->left == nullptr && root->right == nullptr) {
return nullptr;
}
else if (root->left != nullptr && root->right == nullptr) {
if (root->val < low) return nullptr;
else return trimBST(root->left, low, high);
}
else if (root->left == nullptr && root->right != nullptr) {
if (root->val > high) return nullptr;
else return trimBST(root->right, low, high);
}
else {
if (root->val < low) return trimBST(root->right, low, high);
else return trimBST(root->left, low, high);
}
}
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
};
108.将有序数组转换为二叉搜索树
一遍过,但是用了额外空间截取数组片段,可以通过操作下标的方式来使空间复杂度为O(1)。
538.把二叉搜索树转换为累加树
这道题理解题目意思直接秒。
974

被折叠的 条评论
为什么被折叠?



