二叉排序树

二叉排序树(Binary Sort Tree,简称BST),又称二叉查找树,是红黑树、AVL树等的基础。它或是一棵空树,或者是具有下列性质的一棵二叉树:

1、若它的左子树不空,则左子树上所有节点的值均小于它的根节点的值;

2、若它的右子树不空,则右子树上所有节点的值均大于它的根节点的值;

3、它的左右子树也分别为二叉排序树。

 已知,某树的先序遍历为:4, 2, 1 ,0, 3, 5, 9, 7, 6, 8. 中序遍历为: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. 请画出该树。

下面的一棵树即为二叉排序树:

二叉排序树的创建

#include <iostream>  
using namespace std;  

// BITree的结点  
typedef struct BiTNode  
{  
	int key;  
	struct BiTNode *lchild, *rchild;  
}BiTNode, *BITree;  

// 在给定的BITree中插入结点,其数据域为element, 使之称为新的BITree  
bool BITreeInsert(BiTNode * &p, int element)  
{  
	if(NULL == p) // 空树  
	{  
		p = new BiTNode;  
		p->key = element;  
		p->lchild = p->rchild = NULL;  
		return true;  
	}  

	if(element == p->key) // BITree中不能有相等的值  
		return false;  

	if(element < p->key)  // 递归  
		return BITreeInsert(p->lchild, element);  

	return BITreeInsert(p->rchild, element); // 递归  
}  

// 建立BITree  
void createBITree(BiTNode * &T, int a[], int n)  
{  
	T = NULL;   
	int i;  
	for(i = 0; i < n; i++)  
	{  
		BITreeInsert(T, a[i]);  
	}  
}  

//后续遍历销毁二叉树  
void freeTree(BiTNode* root)  
{  
	if (root!=NULL)  
	{  

		if (root->lchild)  
		{  
			freeTree(root->lchild);  
			root->lchild = NULL;  
		}  
		if (root->rchild)  
		{  
			freeTree(root->rchild);  
			root->rchild = NULL;  
		}  
		if (root!=NULL)  
		{  
			free(root);  
			root=NULL;  
		}  
	}  
}  

// 先序遍历  
void preOrderTraverse(BITree T)  
{  
	if(T)  
	{  
		cout << T->key << " ";  
		preOrderTraverse(T->lchild);  
		preOrderTraverse(T->rchild);  
	}  
}  

// 中序遍历  
void inOrderTraverse(BITree T)  
{  
	if(T)  
	{  
		inOrderTraverse(T->lchild);  
		cout << T->key << " ";  
		inOrderTraverse(T->rchild);  
	}  
}  

int main()  
{  
	int a[10] = {4, 5, 2, 1, 0, 9, 3, 7, 6, 8};  
	int n = 10;  
	BITree T;  

	// 并非所有的a[]都能构造出BITree,所以,最好对createBITree的返回值进行判断  
	createBITree(T, a, n);  

	preOrderTraverse(T);  
	cout << endl;  

	inOrderTraverse(T);  
	cout << endl;  

	freeTree(T);
	system("pause");
	return 0;  
}  





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值