SCAU 数据结构实验5 8608 实现二叉排序树的各种算法(2)
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <stack>
#include <queue>
using namespace std;
typedef struct node
{
int key;
struct node *lChild, *rChild;
} Node, *BST;
void creatBST(BST &T,int ele)
{
if(T==NULL)
{
T=new Node;
T->key=ele;
T->lChild=NULL;
T->rChild=NULL;
return;
}
else
{
if(ele==T->key) return;
if(ele<T->key) creatBST(T->lChild,ele);
else creatBST(T->rChild,ele);
}
}
void findBST(BST T,int ele)
{
if(!T)
{
cout << 0 << endl;
return;
}
if(T->key==ele)
{
cout << 1 << endl;
return;
}
else if(T->key > ele)
findBST(T->lChild,ele);
else if(T->key < ele)
findBST(T->rChild,ele);
}
void firsttravel(BST T)
{
if(T)
{
cout << T->key << " ";
firsttravel(T->lChild);
firsttravel(T->rChild);
}
}
void midtravel(BST T)
{
if(T)
{
midtravel(T->lChild);
cout << T->key << " ";
midtravel(T->rChild);
}
}
void lasttravel(BST T)
{
if(T)
{
lasttravel(T->lChild);
lasttravel(T->rChild);
cout << T->key << " ";
}
}
void insertBST(BST T,int ele)
{
if(T->key==ele) return;
Node *p=new Node;
p->key=ele;
p->lChild=NULL;
p->rChild=NULL;
if(T->key > ele)
{
if(T->lChild==NULL)
{
T->lChild=p;
return;
}
else
insertBST(T->lChild,ele);
}
if(T->key < ele)
{
if(T->rChild==NULL)
{
T->rChild=p;
return;
}
else
insertBST(T->rChild,ele);
}
}
void InOrderNor(BST T)
{
stack<BST> s;
Node *cur = T;
while (cur != NULL || !s.empty())
{
while (cur != NULL)
{
s.push(cur);
cur = cur->lChild;
}
Node *top = s.top();
s.pop();
cout << top->key << " ";
cur = top->rChild;
}
}
void LevelOrder(BST T)
{
queue<Node *> q;
if(!T) return;
q.push(T);
BST S;
while(!q.empty())
{
S=q.front();
q.pop();
cout << S->key <<" " ;
if(S->lChild!=NULL)
q.push(S->lChild);
if(S->rChild!=NULL)
q.push(S->rChild);
}
return;
}
void swapBST(BST T )
{
if(!T) return;
Node *p=new Node;
p=T->lChild;
T->lChild=T->rChild;
T->rChild=p;
swapBST(T->lChild);
swapBST(T->rChild);
}
int height(BST T)
{
if(!T) return 0;
else
{
int l=height(T->lChild);
int r=height(T->rChild);
return 1+max(l,r);
}
}
int getCount(BST T)
{
if (T == NULL)
{
return 0;
}
if (T->lChild == NULL && T->rChild == NULL)
{
return 1;
}
return getCount(T->lChild) + getCount(T->rChild);
}
int main()
{
int n,m;
cin >> n;
int k;
BST T=NULL;
for(int i=0; i<n; i++)
{
cin >> k;
creatBST(T,k);
}
firsttravel(T);
cout << endl;
midtravel(T);
cout << endl;
lasttravel(T);
cout << endl;
int ele;
cin >> ele;
findBST(T,ele);
cin >> ele;
findBST(T,ele);
cin >> ele;
insertBST(T,ele);
firsttravel(T);
cout << endl;
midtravel(T);
cout << endl;
lasttravel(T);
cout << endl;
InOrderNor(T);
cout << endl;
LevelOrder(T);
cout << endl;
swapBST(T);
firsttravel(T);
cout << endl;
midtravel(T);
cout << endl;
lasttravel(T);
cout << endl;
swapBST(T);
firsttravel(T);
cout << endl;
midtravel(T);
cout << endl;
lasttravel(T);
cout << endl;
cout << height(T) << endl;
cout << getCount(T);
return 0;
}