Asp.net 学习资料

伦惠峰

二叉排序树操作

#include<iostream.h>
#include<strstrea.h>
struct BTreeNode
{
 int data;
 BTreeNode *left;
 BTreeNode *right;
 int count;
};

void Inorder(BTreeNode* &BST)//中序遍历
{
 if(BST!=NULL){
   Inorder(BST->left);
   cout<<BST->data<<" ";
   Inorder(BST->right);
 }
}

int Find(BTreeNode* &BST,int item)
{
 if(BST==NULL)
  return 0;
 else{
  if(item==BST->data)
  {
   item=BST->data;
   return 1;
  }
  else if(item<BST->data)
   return Find(BST->left,item);
  else
      return Find(BST->right,item);
 }
}


void Insert(BTreeNode* &BST,int item)
{
 if(BST==NULL)
 {
  BTreeNode* p=new BTreeNode;
  p->data=item;
  p->left=p->right=NULL;
  BST=p;
 }
 

 else if(item<BST->data)
  Insert(BST->left,item);
 else
  Insert(BST->right,item);
}

void Insert2(BTreeNode* &BST,int item)
{
 
 if(Find(BST,item)==0)
 {
  Insert(BST,item);
  BST->count=1;
 }
 
 else
  BST->count++;
}

void Postorder(BTreeNode* &BT)//后序遍历
{
 if(BT!=NULL){
   Postorder(BT->left);
   Postorder(BT->right);
   cout<<BT->data<<" ";
 }
}

void PrintBTree(BTreeNode* BT)//输出二叉树
{
 if(BT!=NULL)
 {
  cout<<BT->data;
  if(BT->left!=NULL||BT->right!=NULL)
  {
   cout<<'(';
   PrintBTree(BT->left);
   if(BT->right!=NULL)
    cout<<',';
   PrintBTree(BT->right);
   cout<<')';
  }
 }
}


int FindMax(BTreeNode* &BST)
{
 int max;
 BTreeNode *t=BST;
 while(t->right!=NULL)//记住是t->right!=NULL而不是t!=NULL
  t=t->right;
 max=t->data;
 return max;
}
  
   


void main()
{
 BTreeNode *a;
 a=NULL;
 int item;
 for(int i=0;i<4;i++)
 {
  cin>>item;
  Insert2(a,item);
 }
 cout<<"输入结束"<<endl;
 Inorder(a);
 PrintBTree(a);
 cout<<Find(a,30)<<endl;
 cout<<endl;
 cout<<FindMax(a);
 
 
}

posted on 2007-08-13 21:35  伦惠峰  阅读(207)  评论(0)    收藏  举报

导航