//BST.h
#pragma once
#include<stack>
#include<queue>
#include<iostream>
using namespace std;
typedef char ElemType;
typedef struct node {
ElemType data;
struct node* lchild;
struct node* rchild;
}*BST,BSTree;
int Creat(BST &root, char *S)
{
if (S[0] == '#')
{
root = NULL;
return 1;
}
else
{
root = new BSTree;
root->data = S[0];
int n = Creat(root->lchild, S + 1);
int m = Creat(root->rchild, S + n + 1);
return m + n + 1;
}
}
void Pro_Print(BST root)//前序遍历
{
if (root)
{
cout << root->data;
Pro_Print(root->lchild);
Pro_Print(root->rchild);
}
}
void ProPrint(BST root)//栈实现前序遍历
{
stack<BSTree> S;
BST p=root;
while (p||S.size()>0)
{
while (p)
{
cout << p->data;
S.push(*p);
p = p->lchild;
}
if (S.size() > 0)
{
p =&( S.top());
S.pop();
p = p->rchild;
}
}
}
void In_Print(BST root)//中序遍历
{
if (root)
{
In_Print(root->lchild);
cout << root->data;
In_Print(root->rchild);
}
}
void Post_Print(BST root)//后序遍历
{
if (root)
{
Post_Print(root->lchild);
Post_Print(root->rchild);
cout << root->data;
}
}
bool Find(BST root, ElemType data)//递归查找
{
if (root == NULL)
return false;
if (data <= root->data)
Find(root->lchild, data);
else if (data > root->data)
Find(root->rchild, data);
return true;
}
bool find(BST root, ElemType data)//非递归查找
{
if (root == NULL)
return false;
while (root != NULL)
{
if (data == root->data)
return true;
else if (data <= root->data)
root = root->lchild;
else
root = root->rchild;
}
}
int SizeOfTree(BST root)
{
if (!root)
return 0;
else
return (SizeOfTree(root->lchild) + SizeOfTree(root->rchild) + 1);
}
int SizeOfLeaf(BST root)
{
if (!root)
return 0;
else if (root->lchild == NULL&&root->rchild == NULL)
return 1;
else
return (SizeOfLeaf(root->lchild) + SizeOfLeaf(root->rchild));
}
int Height(BST root)
{
int lh,rh;
if (!root)
return 0;
else {
lh = Height(root->lchild);
rh = Height(root->rchild);
if (lh > rh)
return lh + 1;
else
return rh + 1;
}
}
void Level(BST root)
{
queue<BSTree> Q;
BST temp;
BSTree P;
if (!root)
return;
Q.push(*root);
while (Q.size()>0)
{
P = Q.front();
temp = &P;
Q.pop();
cout << temp->data;
if (temp->lchild)
Q.push(*(temp->lchild));
if (temp->rchild)
Q.push(*(temp->rchild));
}
}
void Destory(BST &root)//销毁
{
if (root)
{
if(root->lchild)
Destory(root->lchild);
if(root->rchild)
Destory(root->rchild);
root = NULL;
}
}
//main.cpp
#include"BST.h"
void main()
{
BST root;
char *S = "6321###4##8##";
Creat(root, S);
cout << "前序遍历:";
ProPrint(root);
cout << endl;
cout << "中序遍历:";
In_Print(root);
cout << endl;
cout << "后序遍历:";
Post_Print(root);
cout << endl;
cout << "层次遍历:";
Level(root);
cout << endl;
char a = '4';
if (find(root, a))
cout << "Find!" << endl;
else
cout << "Not Find!" << endl;
cout << "结点数:" << SizeOfTree(root) << endl;
cout << "叶子数:" << SizeOfLeaf(root) << endl;
cout << "高度:" << Height(root) << endl;
Destory(root);
cout << "销毁后:";
ProPrint(root);
cout << endl;
}