235. 二叉搜索树的最近公共祖先
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
分析:
1、利用二叉搜索树 排大小的性质——对于公共祖先的情况,应当是 落在[p,q]或者[q,p]区间内
2、按照前序去查找,找到了之后直接返回
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if(root==NULL) return NULL;
int x=root->val;
if(x>=fmin(p->val,q->val) && x<=fmax(p->val,q->val)){
return root;
}
if(lowestCommonAncestor(root->left,p,q)) return lowestCommonAncestor(root->left, p, q);
return lowestCommonAncestor(root->right, p, q);
}
701.二叉搜索树中的插入操作
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据保证,新值和原始二叉搜索树中的任意节点值都不同。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。
struct TreeNode* f(struct TreeNode* root, int val){
if(root==NULL ){
printf("%d",1);
struct TreeNode* a=(struct TreeNode* )malloc(sizeof(struct TreeNode));
a->val=val;
a->left=NULL;
a->right=NULL;
return a;
}
if(root->val >val) root->left=f(root->left,val);
else root->right=f(root->right,val);
return root;
}
struct TreeNode* insertIntoBST(struct TreeNode* root, int val) {
root=f(root,val);
return root;
}
450.删除二叉搜索树中的节点
给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。
分析:
- 第一种情况:没找到删除的节点,遍历到空节点直接返回了
- 找到删除的节点
- 第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
- 第三种情况:删除节点的左孩子为空,右孩子不为空,删除节点,右孩子补位,返回右孩子为根节点
- 第四种情况:删除节点的右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
- 第五种情况:左右孩子节点都不为空,则将删除节点的左子树头结点(左孩子)放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。
- 利用二叉搜索树的性质,减少left right的讨论!
struct TreeNode* deleteNode(struct TreeNode* root, int key){
if(root==NULL) return NULL;
if(root->val==key){
struct TreeNode* a=root->left;
struct TreeNode* b=root->right;
if(a==NULL && b==NULL) {
free(root);
return NULL;
}
else if(a==NULL && b!=NULL) {
free(root);
return b;
}
else if(a!=NULL && b==NULL) {
free(root);
return a;
}
else {
free(root);
struct TreeNode* c=b;
while(c->left!=NULL) {
c=c->left;
}
c->left=a;
return b;
}
}
if(key>root->val) root->right=deleteNode(root->right, key);
if(key<root->val) root->left=deleteNode(root->left, key);
return root;
}