二叉排序树逻辑分析及代码实现
作者:互联网
二叉排序树主要有插入,删除这两个操作,二叉排序树是基于中序输出实现的,所以需满足左指针节点数据<节点数据<右指针节点数据
首先二叉排序树的数据类型定义为结构体,数据包含数据,节点的左指针,节点的右指针
1 struct node 2 { 3 int key; 4 node* left; 5 node* right; 6 };
接着是二叉排序树的插入操作,基本逻辑如下图:
代码实现如下:
1 void insert(int key, node* Node) 2 { 3 node* temp1 = Node;//指针1 4 node* pre = NULL;//指针2 5 while (temp1 != NULL) 6 { 7 pre = temp1; 8 if (key < temp1->key) temp1 = temp1->left; 9 else temp1 = temp1->right; 10 } 11 if (key < pre->key) 12 { 13 pre->left = new node; 14 pre->left->key = key; 15 pre->left->left = NULL; 16 pre->left->right = NULL; 17 } 18 else 19 { 20 pre->right = new node; 21 pre->right->key = key; 22 pre->right->left = NULL; 23 pre->right->right = NULL; 24 } 25 }View Code
最后是删除操作,二叉排序树删除操作有些复杂,考虑情况很多,逻辑梳理如下图:
代码如下:
1 void node_delete(int key, node* Node) 2 { 3 if (Node == NULL)//(特殊情况考虑) 4 { 5 return; 6 } 7 else 8 { 9 node* delete_node = Node; 10 if (delete_node->key == key) 11 { 12 node* father_node = prev(root,Node, key);//用于找到删除节点的父亲是谁 13 if (delete_node->right == NULL)//删除节点只有左儿子或没有儿子 14 { 15 node* son_node = delete_node->left; 16 if (delete_node == root)//删除节点是根节点 17 { 18 delete_node->left = NULL; 19 root = son_node; 20 delete delete_node; 21 } 22 else if (father_node->left != NULL && father_node->left->key == key)//删除节点不是根节点并且删除节点是其父亲的左儿子 23 { 24 father_node->left = son_node; 25 delete delete_node; 26 } 27 else//删除节点不是根节点并且删除节点是其父亲的右儿子 28 { 29 father_node->right = son_node; 30 delete delete_node; 31 } 32 } 33 else if (delete_node->left == NULL) 34 { 35 node* son_node = delete_node->right; 36 if (delete_node == root)//删除节点是根节点 37 { 38 delete_node->right = NULL; 39 root = son_node; 40 delete delete_node; 41 } 42 else if (father_node->left != NULL && father_node->left->key == key)//删除节点不是根节点并且删除节点是其父亲的左儿子 43 { 44 father_node->left = son_node; 45 delete delete_node; 46 } 47 else//删除节点不是根节点并且删除节点是其父亲的右儿子 48 { 49 father_node->right = son_node; 50 delete delete_node; 51 } 52 } 53 else//删除节点有两个儿子 54 { 55 node* t1 = Node->left; 56 node* t2 = Node; 57 while (t1 ->right!= NULL) 58 { 59 t2 = t1; 60 t1 = t1->right; 61 }//t2定位到左子树的最大值的父亲,t2的右孩子是t1 62 if (t2 != Node) 63 { 64 Node->key = t1->key; 65 node* delete_node = t1; 66 t2->right = t1->left; 67 delete delete_node; 68 } 69 else//(特殊情况考虑) 70 { 71 Node->left = t1->left; 72 delete t1; 73 } 74 } 75 } 76 else if (key < delete_node->key) node_delete(key, delete_node->left); 77 else node_delete(key, delete_node->right); 78 } 79 } 80 node* prev(node* root,node* Node, int key) 81 { 82 if (Node == root||root==NULL)//树为空集或查询的是根节点木有父亲(特殊情况考虑) 83 { 84 return Node; 85 } 86 else 87 { 88 if (root->left != NULL && root->left->key == key) return root; 89 else if (root->right != NULL && root->right->key == key) return root; 90 else if (key < root->key) return prev(root->left, Node, key); 91 else return prev(root->right,Node, key); 92 } 93 94 }View Code
标签:node,right,代码,二叉,key,left,排序,节点,delete 来源: https://www.cnblogs.com/wangxiaomeidegou/p/16530557.html