235. 二叉搜索树的最近公共祖先
题目:力扣
//二叉树的普通方法,后序遍历求公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr) return root;
if(root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left,p,q);
TreeNode* right = lowestCommonAncestor(root->right,p,q);
if(left != nullptr && right != nullptr) return root;
else if(left != nullptr && right == nullptr) return left;
else if(left == nullptr && right != nullptr) return right;
else return nullptr;
}
};
//利用搜索二叉树的性质,p,q一定分别在公共祖先的左子树和右子树(或者本身),从上往下遍历就可以
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);
}else if(root->val > p->val && root->val > q->val){
return lowestCommonAncestor(root->left,p,q);
}else{
return root;
}
}
};
701.二叉搜索树中的插入操作
题目:力扣
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(root == nullptr){
root = new TreeNode(val);
return root;
}
if(root->val < val){
if(root->right == nullptr){
root->right = new TreeNode(val);
}else{
insertIntoBST(root->right,val);
}
}else{
if(root->left == nullptr){
root->left = new TreeNode(val);
}else{
insertIntoBST(root->left,val);
}
}
return root;
}
};
450.删除二叉搜索树中的节点
题目:力扣
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == nullptr) return nullptr;
if(root->val == key){
if(root->left == nullptr && root->right == nullptr) return nullptr;
else if(root->left == nullptr && root->right != nullptr) return root->right;
else if(root->right == nullptr && root->left != nullptr) return root->left;
else if(root->right != nullptr && root->left != nullptr) {
TreeNode* next = root->right;
while(next->left != nullptr){
next = next->left;
}
next->left = root->left;
return root->right;
}
}else if(root->val < key){
root->right = deleteNode(root->right,key);
}else{
root->left = deleteNode(root->left,key);
}
return root;
}
};
总结
题型:二叉搜索树的插入和删除
技巧:运用好二叉搜索树的性质,问题就迎刃而解。