#include<iostream>//二叉树的建立,遍历算法(非递归),递归在其他代码中,深度算法,叶子节点个数算法。
#include<stack>
#include<queue>
using namespace std;
typedef struct tree
{
char data;
struct tree *lchild,*rchild;
}tree,*bitree;
typedef struct post
{
bitree bit;
char tag;
}post,*postorder;
int createtree(bitree &T)
{
char data;
cin>>data;
if(data==',') {T=NULL;}
else
{
T=new tree;
T->data=data;
createtree(T->lchild);
createtree(T->rchild);
}
return 0;
}
void preorder(bitree T)
{
stack<bitree>stack;
bitree p=T;
while(p||!stack.empty())
{
if(p!=NULL)
{
stack.push(p);
cout<<p->data;
p=p->lchild;
}
else
{
p=stack.top();
stack.pop();
p=p->rchild;
}
}
}
void inorder(bitree T)
{
stack<bitree>stack;
bitree p=T;
while(p||!stack.empty())
{
if(p!=NULL)
{
stack.push(p);
p=p->lchild;
}
else
{
p=stack.top();
cout<<p->data;
stack.pop();
p=p->rchild;
}
}
}
void postordertree(bitree T)
{
stack<postorder>stack;
bitree p=T;
postorder bt;
while(p||!stack.empty())
{
while(p!=NULL)
{
bt=new post;
bt->bit=p;
bt->tag='L';
stack.push(bt);
p=p->lchild;
}
while(!stack.empty() && (stack.top())->tag=='R')
{
bt=stack.top();
stack.pop();
cout<<bt->bit->data;
}
if(!stack.empty())
{
bt=stack.top();
bt->tag='R';
p=bt->bit;
p=p->rchild;
}
}
}
void levelorder(bitree T)
{
queue<bitree>queue;
bitree p=T;
queue.push(p);
while(!queue.empty())
{
p=queue.front();
cout<<p->data;
queue.pop();
if(p->lchild!=NULL)
queue.push(p->lchild);
if(p->rchild!=NULL)
queue.push(p->rchild);
}
}
int high_count(bitree T)
{
int left,right,high;
if(!T) {return 0;}
left=high_count(T->lchild);
right=high_count(T->rchild);
high=(left>right?left:right)+1;
return high;
}
int yezi_count(bitree T,int &n)
{
if(T)
{
if(T->lchild==NULL && T->rchild==NULL)
n++;
yezi_count(T->lchild,n);
yezi_count(T->rchild,n);
}
return n;
}
int main()
{
int s=0;
bitree T;
createtree(T);
preorder(T);
cout<<"\n";
inorder(T);
cout<<"\n";
postordertree(T);
cout<<"\n";
levelorder(T);
cout<<"\n";
int h=high_count(T);
cout<<h<<endl;
int m=yezi_count(T,s);
cout<<m<<endl;
return 0;
}
二叉树的基本算法
最新推荐文章于 2022-12-06 16:51:47 发布