二叉排序树(二叉搜索树)的构建

二叉排序树(也叫二叉搜索树、二叉查找树)满足对树上任意一个结点,数值必定大于等于其左子树上任意结点的数值,必小于等于其右子树上任意结点的数值。

构建二叉排序树的方法:

对于插入的数据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);
}

 

  • 8
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值