一、235 二叉搜索树的最近公共祖先
//递归
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if(root == NULL)
return NULL;
if(root->val>p->val&&root->val>q->val){
struct TreeNode*left = lowestCommonAncestor(root->left,p,q);
if(left!=NULL)
return left;
}
if(root->val<p->val&&root->val<q->val){
struct TreeNode*right = lowestCommonAncestor(root->right,p,q);
if(right!=NULL)
return right;
}
return root;
}
//迭代
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q){
while(root!=NULL){
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 NULL;
}
二、701 二叉搜索树中的插入操作
struct TreeNode* insertIntoBST(struct TreeNode* root, int val) {
if(root==NULL){//找到要插入节点的位置
struct TreeNode*node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
//初始化新节点的左右节点
node->left = NULL;
node->right = NULL;
return node;
}
if(val<root->val)
root->left = insertIntoBST(root->left, val);
if(val>root->val)
root->right = insertIntoBST(root->right, val);
return root;
}
三、450 删除二叉搜索树中的节点
struct TreeNode* deleteNode(struct TreeNode* root, int key) {
if(root == NULL)//没找到
return NULL;
if(root->val == key){//找到后分4种情况
if(root->left==NULL&&root->right == NULL)
return NULL;
else if(root->left!=NULL&&root->right==NULL)
return root->left;
else if(root->left == NULL&&root->right!=NULL)
return root->right;
else{//左不空右不空
struct TreeNode*cur = root->right;
while(cur->left!=NULL){
cur = cur->left;
}
cur->left = root->left;
return root->right;
}
}
if(key<root->val)
root->left = deleteNode(root->left, key);
if(key>root->val)
root->right = deleteNode(root->right, key);
return root;
}