#include <iostream>
#include <stack>
using namespace std;
struct BiNode
{
char data;
BiNode *lchild,*rchild;
};
class Tree
{
private:
BiNode *bt;
public:
BiNode* Create(BiNode* bt);
void PreOrder(BiNode* bt);
void PostOrder(BiNode *bt);
void InOrder(BiNode *bt);
/*非递归遍历系列*/
void PreOrderNoRecursion(BiNode *bt);
void PostOrderNoRecursion(BiNode *bt);
void InOrderNoRecursion(BiNode *bt);
};
BiNode* Tree::Create(BiNode *bt)
{
char ch;
cin>>ch;
if(ch=='#')bt=NULL;
else{
bt=new BiNode;
bt->data=ch;
bt->lchild = Create(bt->lchild);
bt->rchild = Create(bt->rchild);
}
return bt;
}
void Tree::PreOrder(BiNode* bt){
if(bt==NULL)return;
else{
cout<<bt->data;
PreOrder(bt->lchild);
PreOrder(bt->rchild);
}
}
void Tree::InOrder(BiNode *bt){
if(bt==NULL)return;
else{
InOrder(bt->lchild);
cout<<bt->data;
InOrder(bt->rchild);
}
}
void Tree::PostOrder(BiNode *bt){
if(bt==NULL)return;
else{
PostOrder(bt->lchild);
PostOrder(bt->rchild);
cout<<bt->data;
}
}
///非递归方法遍历二叉树/
void Tree::PreOrderNoRecursion(BiNode *bt){
stack<BiNode*> stack;
cout<<bt->data;
stack.push(bt);
while(bt!=NULL){
if(bt->lchild!=NULL){
bt=bt->lchild;
stack.push(bt);
cout<<bt->data;
}
else if(bt->rchild!=NULL){
bt=stack.top()->rchild;
stack.pop();
cout<<bt->data;
stack.push(bt);
}
else{
if(!stack.empty())
stack.pop();
else return;
}
}
}
//中序遍历二叉树///
void Tree::InOrderNoRecursion(BiNode *bt){
stack<BiNode*> stack;
while(!stack.empty()||bt!=NULL){
while(bt!=NULL){
stack.push(bt);
bt=bt->lchild;
}
if(!stack.empty()){
bt=stack.top();
stack.pop();
cout<<bt->data;
bt=bt->rchild;
}
}
}
///二叉树后续遍历///
void Tree::PostOrderNoRecursion(BiNode *bt){
}
///Main.cpp///
#include "BiTree.h"
int main(){
//只可以测试单个,因为每次root所指向的内存都回变化!
Tree tree;
BiNode *root=NULL;
root=tree.Create(root);
//tree.PreOrder(root);
//tree.InOrder(root);
//tree.PostOrder(root);
//tree.PreOrderNoRecursion(root);
tree.InOrderNoRecursion(root);
}
二叉树的创建和遍历
最新推荐文章于 2022-12-14 19:54:31 发布