代码随想录day19 235. 二叉搜索树的最近公共祖先 、701.二叉搜索树中的插入操作 、 450.删除二叉搜索树中的节点
235. 二叉搜索树的最近公共祖先
不算难,分类讨论即可
class Solution {
public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {if (root == nullptr) {return root;}if (root->val < p->val && root->val < q->val) {return lowestCommonAncestor(root->right, p, q);}if (root->val > p->val && root->val > q->val) {return lowestCommonAncestor(root->left, p, q);}return root;}
};
701.二叉搜索树中的插入操作
比较简单,自己可以写出
class Solution {
public:TreeNode* insertIntoBST(TreeNode* root, int val) {if (root == nullptr) {return new TreeNode(val);}if (root->val > val) {root->left = insertIntoBST(root->left, val);}if (root->val < val) {root->right = insertIntoBST(root->right, val);}return root;}
};
450.删除二叉搜索树中的节点
这道题有点麻烦,我的问题主要出在同时拥有左右节点得策略,想返回右子树的最左结点,结果总是有点问题,不如卡哥的返回右节点的方法好
class Solution {
public:TreeNode* deleteNode(TreeNode* root, int key) {if (root == nullptr) {return root;}if (root->val > key) {root->left = deleteNode(root->left, key);return root;} if (root->val < key) {root->right = deleteNode(root->right, key);return root;}TreeNode *res = root;if (root->left == nullptr) {res = root->right;delete root;return res;}if (root->right == nullptr) {res = root->left;delete root;return res;}res = root->right;TreeNode *cur = root->right;while (cur->left != nullptr) {cur = cur->left;}cur->left = root->left;delete root;return res;}
};