二叉搜索树可以提供对数时间的插入和访问,其节点的放置规则是:任何一个节点的键值一定大于其左树节点的键值,而且小于其右树节点的值。
根据这个规则我们来完成二叉搜索树的实现。
#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;
}
}