二叉排序树(也叫二叉搜索树、二叉查找树)满足对树上任意一个结点,数值必定大于等于其左子树上任意结点的数值,必小于等于其右子树上任意结点的数值。
构建二叉排序树的方法:
对于插入的数据x
1.若当前树为空,则x为其根结点。
2.若x小于当前结点,则插入其左子树。若x大于当前结点,则插入其右子树。
若对二叉排序树进行中序遍历,那么其遍历结果必然是一个递增序列,这也是二叉排序树名字的由来。
二叉排序树用于对无序序列进行排序,并进行动态维护。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct TreeNode
{
char val;
TreeNode *left;
TreeNode *right;
};
TreeNode *creatTree(TreeNode* p)
{
p = (TreeNode*)malloc(sizeof(TreeNode));
p->left = NULL;
p->right = NULL;
return p;
}
void removeTree(TreeNode *p)
{
if (p == NULL)
{
return;
}
removeTree(p->left);
removeTree(p->right);
free(p);
}
//中序遍历二叉树
void inOrder(TreeNode *p)
{
if (p->left != NULL)
{
inOrder(p->left);
}
cout << p->val;
if (p->right != NULL)
{
inOrder(p->right);
}
}
TreeNode * insert(TreeNode *t,char c)
{
if (t == NULL)
{
t = creatTree(t);
t->val = c;
return t;
}
if (c < t->val)
{
t->left = insert(t->left, c);
return t;
}
if( c > t->val )
{
t->right = insert(t->right, c);
return t;
}
}
int main()
{
TreeNode *root = NULL;
root = insert(root, 'c');
root = insert(root, 'd');
root = insert(root, 'a');
root = insert(root, 'f');
root = insert(root, 'b');
root = insert(root, 'e');
root = insert(root, 'g');
inOrder(root);
removeTree(root);
}