?? bitree.cpp
字號:
#include<iostream>
#include<string>
#include"bitree.h"
using namespace std;
template<class T>
BiTree<T>::BiTree( )
{
this->root = Creat( );
}
template<class T>
BiTree<T>::~BiTree(void)
{
Release(root);
}
template<class T>
BiNode<T>* BiTree<T>::Getroot( )
{
return root;
}
template<class T>
void BiTree<T>::PreOrder(BiNode<T> *root)
{
if(root==NULL) return;
else{
cout<<root->data<<" ";
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
template <class T>
void BiTree<T>::InOrder (BiNode<T> *root)
{
if (root==NULL) return; //遞歸調用的結束條件
else{
InOrder(root->lchild); //中序遞歸遍歷root的左子樹
cout<<root->data<<" "; //訪問根結點的數據域
InOrder(root->rchild); //中序遞歸遍歷root的右子樹
}
}
template <class T>
void BiTree<T>::NotRecInOrder (BiNode<T> *root)
{
int top=-1;
BiNode<T> *s[1000];
while(root!=NULL||top!=-1)
{
while(root!=NULL)
{
cout<<root->data<<" ";
s[++top]=root;
root=root->lchild;
}
if(top!=-1)
{
root=s[top--];
root=root->rchild;
}
}
}
template <class T>
void BiTree<T>::PostOrder(BiNode<T> *root)
{
if (root==NULL) return; //遞歸調用的結束條件
else{
PostOrder(root->lchild); //后序遞歸遍歷root的左子樹
PostOrder(root->rchild); //后序遞歸遍歷root的右子樹
cout<<root->data<<" "; //訪問根結點的數據域
}
}
template <class T>
void BiTree<T>::LeverOrder(BiNode<T> *root)
{
const int MaxSize = 100;
int front = 0;
int rear = 0; //采用順序隊列,并假定不會發生上溢
BiNode<T>* Q[MaxSize];
BiNode<T>* q;
if (root==NULL) return;
else{
Q[rear++] = root;
while (front != rear)
{
q = Q[front++];
cout<<q->data<<" ";
if (q->lchild != NULL) Q[rear++] = q->lchild;
if (q->rchild != NULL) Q[rear++] = q->rchild;
}
}
}
template <class T>
BiNode<T>* BiTree<T>::Creat( )
{
BiNode<T>* root;
T ch;
cout<<"請輸入創建一棵二叉樹的結點數據"<<endl;
cin>>ch;
if (ch=="#") root = NULL;
else{
root = new BiNode<T>; //生成一個結點
root->data=ch;
root->lchild = Creat( ); //遞歸建立左子樹
root->rchild = Creat( ); //遞歸建立右子樹
}
return root;
}
template<class T>
void BiTree<T>::Release(BiNode<T>* root)
{
if (root != NULL){
Release(root->lchild); //釋放左子樹
Release(root->rchild); //釋放右子樹
delete root;
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -