代码随想录算法训练营day20、21 | 701.二叉搜索树中的插入操作、450.删除二叉搜索树中的节点、669. 修剪二叉搜索树、108.有序数组转换为二叉搜索树、538.把二叉搜索树转换为累加树
701.二叉搜索树中的插入操作
点击查看代码
class Solution {
public:
void preOrder(TreeNode *root, TreeNode *parent, int val) {
if(root == nullptr) {
TreeNode *newNode = new TreeNode(val);
if(val < parent->val) parent->left = newNode;
else parent->right = newNode;
return;
}
if(root->val < val) preOrder(root->right, root, val);
if(root->val > val) preOrder(root->left, root, val);
}
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr) return new TreeNode(val);
preOrder(root, nullptr, val);
return root;
}
};
450.删除二叉搜索树中的节点
有几个特殊用例通过不了,先跳过...
点击查看代码
class Solution {
public:
TreeNode *keypre;
TreeNode *searchKey(TreeNode* root, int key) {
if(root == nullptr) return nullptr;
else if(root->val == key) return root;
else if(root->val > key) {
keypre = root;
return searchKey(root->left, key);
}
else {
keypre = root;
return searchKey(root->right, key);
}
}
void findKeyPreoreNext(TreeNode* root) {
TreeNode *pre = root;
TreeNode *cur = root;
if(root->left != nullptr) {
cur = root->left;
while(cur->right != nullptr) {
pre = cur;
cur = cur->right;
}
swap(root->val, cur->val);
if(cur == pre->right) pre->right = nullptr;
if(cur == pre->left) pre->left = cur->left;
}
else if(root->right != nullptr) {
cur = root->right;
while(cur->left != nullptr) {
pre = cur;
cur = cur->left;
}
swap(root->val, cur->val);
if(cur == pre->right) pre->right = cur->right;
if(cur == pre->left) pre->left = nullptr;
}
}
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == nullptr) return root;
if(root->val == key && root->left == nullptr && root->right == nullptr)
return nullptr;
if(searchKey(root, key) == nullptr) return root;
else if(searchKey(root, key)->left == nullptr && searchKey(root, key)->right == nullptr) {
if(searchKey(root, key) == keypre->left) keypre->left = nullptr;
if(searchKey(root, key) == keypre->right) keypre->right = nullptr;
return root;
}
else findKeyPreoreNext(searchKey(root, key));
return root;
}
};
69.修剪二叉搜索树
难,跳过
108.将有序数组转换为二叉搜索树
难,跳过
538.把二叉搜索树转换为累加树
点击查看代码
class Solution {
public:
TreeNode *pre = nullptr;
void inOrder(TreeNode *root) {
if(root == nullptr) return;
inOrder(root->right);
if(pre != nullptr) root->val += pre->val; //第一个节点值最大,无需累加
pre = root;
inOrder(root->left);
}
TreeNode* convertBST(TreeNode* root) {
inOrder(root);
return root;
}
};
通过右 中 左遍历,从元素最大的节点开始处理,一直处理到元素最小的节点,逐步累加节点值即可
2025/03/02

浙公网安备 33010602011771号