C++二叉搜索树的实现

 二叉搜索树可以提供对数时间的插入和访问,其节点的放置规则是:任何一个节点的键值一定大于其左树节点的键值,而且小于其右树节点的值。

根据这个规则我们来完成二叉搜索树的实现。

#include<iostream>
using namespace std;
struct tree           //创建树节点 
{
	int data;
	tree*left,*right;
};
class BST            //创建二叉搜索树 
{
	static int m; 
public:
	tree *root;
	BST()
	{
		root=NULL;
	}
	void create_tree(int);
	void preorder(tree*);
	void inorder(tree*);
	void Postorder(tree *); 
	int count(tree*);
	int findleaf(tree*);
};
int BST::m=0;
void BST::create_tree(int x)//将值存入二叉搜索树中 
{
	tree *node=new tree;
	node->data=x;
	node->left=NULL;
	node->right=NULL;
	if(root==NULL)
	root=node;
    else
    {
    	tree *back;
		tree *current=root;
		while(current!=NULL)
		{
		    back=current;
		    if(current->data>x)
		    current=current->left;
		    else
		    current=current->right;
		}
		if(back->data>x)
		back->left=node;
		else
		back->right=node;
	}
}
int BST::count(tree *temp)      //计算节点个数,递归的方法。
{
    if(temp==NULL)
        return 0;
    else
        return count(temp->left)+count(temp->right)+1;      
}
int BST::findleaf(tree *temp)         //计算二叉搜索树叶子的数量 
{
	if(temp==NULL)
	return 0;
	if(temp->left==NULL&&temp->right==NULL)
	m++;
	else
	{
		findleaf(temp->left);
		findleaf(temp->right);
	}
}
void BST::preorder(tree*temp)        //先序遍历,递归的方法。 
{
	if(temp!=NULL)
	{
		cout<<temp->data<<" ";
		preorder(temp->left);
		preorder(temp->right);
	}
}
void BST::inorder(tree*temp)          //中序遍历,递归的方法。
{
	if(temp!=NULL)
	{
		inorder(temp->left);
		cout<<temp->data<<" ";		
		inorder(temp->right);
	}
}
void BST::Postorder(tree *temp)     //后序遍历,递归的方法。
{
    if(temp!=NULL)
    {
        Postorder(temp->left);
        Postorder(temp->right);
        cout<<temp->data<<" ";
    }
}
int main()
{
	
	int m,n;
	while(cin>>m)
	{
		if(m==0)
		break;
		BST b;
		while(m--)
		{
			cin>>n;
			b.create_tree(n);
		}
		
		cout<<b.count(b.root)<<endl;
		cout<<b.findleaf(b.root)<<endl;
		
		b.inorder(b.root);
		cout<<endl;
		b.preorder(b.root);
		cout<<endl;
		b.Postorder(b.root);
		cout<<endl; 
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值