二叉搜索树又称为二叉排序树,首先二叉搜索树是一棵二叉树,所谓二叉树,就是"任意节点最多允许两个子节点",这两个子节点称为左右子节点。
二叉搜索树的性质:
1、若左子树不空,则左子树上的所有节点的值均小于其根节点的值;
2、若右子树不空,则右子树上的所有节点的值均大于其根节点的值;
上图便是一个二叉搜索树,也就是说:任意节点的键值一定大于其左子树中的每一个节点的键值,并小于其右子树中的每一个节点的键值。
下面是自己对二叉搜索树的代码实现:
#include <iostream> using namespace std; struct TreeNode{ int data; TreeNode *left; TreeNode *right; }; //在二叉搜索树查找 TreeNode *search_BST(TreeNode *root, int key) { TreeNode *p = root; while(p) { if(p->data == key) return p; p = (key < p->data) ? p->left : p->right; } return NULL; } //数据插入到二叉搜索树中 void insert_BST(TreeNode **root, int data) { if(root == NULL) return; TreeNode *p = (TreeNode *)malloc((sizeof(struct TreeNode))); p->data = data; p->left = p->right= NULL; if(*root == NULL) { *root = p; return; } if(search_BST(*root, data) != NULL) return; TreeNode *preNode = NULL, *curNode = *root; while(curNode) { preNode = curNode; curNode = (data < curNode->data) ? curNode->left : curNode->right; } if(data < preNode->data) preNode->left = p; else preNode->right = p; } //创建二叉搜索树 void create_BST(TreeNode **root, int *arr, int len) { for(int i = 0; i < len; i++) { insert_BST(root, arr[i]); } } //递归中序遍历树 void minOrderPrint(TreeNode *p) { if(p == NULL) return; minOrderPrint(p->left); cout << p->data << ","; minOrderPrint(p->right); } //递归先序遍历树 void preOrderPrint(TreeNode *p) { if(p == NULL) return; cout << p->data << ","; preOrderPrint(p->left); preOrderPrint(p->right); } //用栈的方式非递归先序遍历(注:先进后出) void preOrderPrintByStack(TreeNode *root) { TreeNode *stack[100], *p = NULL; int top = -1; if(root != NULL) { top++; stack[top] = root; while(top > -1) { p = stack[top]; top--; cout << p->data << ","; if(p->right != NULL) { top++; stack[top] = p->right; } if(p->left != NULL) { top++; stack[top] = p->left; } } } } //删除数据 void delete_BST(TreeNode **root, int data) { TreeNode *p = *root; if(data == p->data) { if(p->left == NULL && p->right == NULL) *root = NULL; else if(p->left == NULL) *root = p->right; else if(p->right == NULL) *root = p->left; else { TreeNode *temp = p->right, *find = NULL; while(temp != NULL) { find = temp; temp = temp->left; } find->left = p->left; p = p->right; *root = p; } } if(data < p->data) { delete_BST(&p->left, data); } if(data > p->data) { delete_BST(&p->right, data); } } int main() { int arr[] = {17,12,19,10,15,18,25,8,11,13,16,22}; int len = sizeof(arr) / sizeof(arr[0]); TreeNode *node = NULL; create_BST(&node, arr, len); preOrderPrint(node); cout << endl; delete_BST(&node, 11); preOrderPrint(node); cout << endl; //preOrderPrintByStack(node); system("pause"); return 0; }