#include<iostream> #include<algorithm> using namespace std; typedef struct treenode { int data; treenode *lchild; treenode *rchild; }*Node; bool Insert(Node &root, int k) { //插入数据 if (root == NULL) { root = new treenode; root->data = k; root->lchild = NULL; root->rchild = NULL; return true; } else { if (k == root->data) { return false; } else { if (k < root->data) { return Insert(root->lchild, k); } else { return Insert(root->rchild, k); } } } } void Create(Node &root, int *A, int n) { //构造二叉树 int i = 0; while (i < n) { Insert(root, A[i]); //插入元素 i++; } } int Next(int *A,int k,int n) { //寻找它的后继 for (int i = 0; i < n; i++) { if (A[i] == k && (i+1)<n ) { return A[i + 1]; } } } Node Delete_one(Node t,int k,int n,int *A) { Node root = t; Node p = NULL; while (root != NULL && k != root->data) { p = root; if (k < root->data) { root = root->lchild; } else { root = root->rchild; } } if (root != NULL) { //找到了这个节点 if (root->lchild == NULL && root->rchild == NULL) { //叶子节点 if (p->lchild == root) { //置为空指针 p->lchild = NULL; } if (p->rchild == root) { //置为空指针 p->rchild = NULL; } return root; } else { if (root->lchild != NULL && root->rchild == NULL) { if (p->lchild == root) { p->lchild = root->lchild; } if (p->rchild == root) { p->rchild = root->lchild; } return root; } else { if (root->lchild == NULL && root->rchild != NULL) { if (p->lchild == root) { p->lchild = root->rchild; } if (p->rchild == root) { p->rchild = root->rchild; } return root; } else { if (root->lchild != NULL && root->rchild != NULL) { Node temp = Delete_one(t, Next(A,n,k),n,A); //获得删除的后继节点 if (p->lchild == root) { p->lchild = temp; temp->lchild = root->lchild; temp->rchild = root->rchild; } if (p->rchild == root) { p->rchild = temp; temp->lchild = root->lchild; temp->rchild = root->rchild; } return root; } } } } } } void Print(Node root) { if (root) { Print(root->lchild); cout << root->data << " "; Print(root->rchild); } } void Delete(Node &root) { if (root) { Delete(root->lchild); Delete(root->rchild); delete root; } } int main() { Node root = NULL; int A[9] = {8,3,2,7,5,4,1,0,6}; Create(root, A, 9); Print(root); cout << endl; sort(A, A + 9); Delete_one(root, 4,9,A); Print(root); Delete(root); //随手删除,好习惯 system("pause"); return 0; }
C++二叉排序树的基本操作
猜你喜欢
转载自blog.csdn.net/coolsunxu/article/details/80517103
今日推荐
周排行