235.二叉搜索树的最近公共祖先
上一篇中可以用一般二叉树的查询方法来看,根据二叉搜索树的特性,那么可以根据需要查找的节点的值;
如果都在目前节点的右侧,只需要从右侧继续查找;
如果都在目前节点的左侧,只需要从左侧继续查找;
如果已经在目前节点的两侧了,那么当前节点就是最近公共祖先了;
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==nullptr) return nullptr;
if(q->val<root->val&&p->val<root->val) {
TreeNode* res=lowestCommonAncestor(root->left,p,q);
if(res!=nullptr) {
return res;
}
}
if(p->val>root->val&&q->val>root->val) {
TreeNode* res=lowestCommonAncestor(root->right,p,q);
if(res!=nullptr) {
return res;
}
}
return root;
}
};
迭代法写的很简单,还是利用了二叉搜索树的特性:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while(root) {
if(root->val>p->val&&root->val>q->val) {
root=root->left;
}else if(root->val<p->val&&root->val<q->val){
root=root->right;
}else{
return root;
}
}
return nullptr;
}
};
701.二叉搜索树的插入操作
迭代法与前面的遍历法是一样的:
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
TreeNode* node=new TreeNode(val);
if(root==nullptr) return node;
TreeNode* pre=root;
TreeNode* p=root;
while(root) {
if(root->val>val) {
pre=root;
root=root->left;
}else{
pre=root;
root=root->right;
}
}
if(pre->val>val) {
pre->left=node;
}else{
pre->right=node;
}
return p;
}
};
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) {
delete root;
return nullptr;
}else if(root->left==nullptr&&root->right!=nullptr){
auto it=root->right;
delete root;
return it;
}else if(root->left!=nullptr&&root->right==nullptr){
auto it=root->left;
delete root;
return it;
}else{
auto it=root->right;
while(it->left) {
it=it->left;
}
TreeNode* node=root->left;
it->left=node;
TreeNode* p=root->right;
delete root;
return p;
}
}else if(root->val>key) {
root->left=deleteNode(root->left,key);
}else{
root->right=deleteNode(root->right,key);
}
return root;
}
};