二叉查找树专题
- 二叉查找树的基本操作
- 查找
- 插入
- 删除
- 二叉查找树的性质
代码来源:晴神《算法笔记》!!
二叉查找树的基本操作
查找
void search(node* root, int x){if(root == NULL){printf("search failed\n");return;}if(root->data == x)printf("%d", x);else if(x < root->data)search(root->lchild, x)elsesearch(root->rchild, x);
}
插入
void insert(node* &root, int x){if(root == NULL){root = newnode(x);return;}if(root->data == x){ //结点已经存在 return;}else if(x < root->data)insert(root->lchild, x);else insert(root->rchild, x);
}
删除
node* findmax(node* root){ //直接前驱 while(root->rchild != NULL){root = root->rchild;}return root;
}
node* findmin(node* root){ //直接后继 while(root->lchild != NULL){root = root->lchild;}return root;
}
void deletenode(node* &root, int x){ //加引号 if(root == NULL){return;}if(root->data == x){if(root->lchild == NULL && root->rchild == NULL)root = NULL;else if(root->lchild != NULL){node* pre = findmax(root->lchild);root->data = pre->data;deletenode(root->lchild, pre->data);}else{node* next = findmin(root->rchild);root->data = next->data;deletenode(root->rchild, next->data);}}else if(x < root->data)deletenode(root->lchild, x);else deletenode(root->rchild, x);
}
二叉查找树的性质
对二叉查找树进行中序遍历,遍历的结果是有序的。