235. 二叉搜索树的最近公共祖先
思路: 二叉搜索树是有序的,因此对他进行遍历时,第一次遇到的节点cur在**[p,q]**时,就为最近公共祖先。
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* cur, TreeNode* p, TreeNode* q) {
if (cur == NULL) return cur;
// 中
if (cur->val > p->val && cur->val > q->val) { // 左
TreeNode* left = lowestCommonAncestor(cur->left, p, q);
if (left != NULL) {
return left;
}
}
if (cur->val < p->val && cur->val < q->val) { // 右
TreeNode* right = lowestCommonAncestor(cur->right, p, q);
if (right != NULL) {
return right;
}
}
return cur;
}
};
701.二叉搜索树中的插入操作
思路: 遍历二叉搜索树,找到空节点插入即可。
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == NULL){
TreeNode* node = new TreeNode(val);
return node;
}
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 == NULL)
return root;
if (root->val > key) root->left = deleteNode(root->left, key);
if (root->val < key) root->right = deleteNode(root->right, key);
if (root->val == key) {
if (root->left == NULL && root->right == NULL) {
delete root;
return NULL;
}
else if(root->left == NULL){
auto retNode = root->right;
delete root;
return retNode;
}
else if(root->right == NULL){
auto retNode = root->left;
delete root;
return retNode;
}
else{
TreeNode* cur = root->right;
while(cur->left != nullptr) {
cur = cur->left;
}
cur->left = root->left;
TreeNode* tmp = root;
root = root->right;
delete tmp;
return root;
}
}
return root;
}
};