作者:嘿听tj说你是被搞出来的 | 来源:互联网 | 2014-11-14 09:57
#include二叉树的建立,遍历算法(非递归),递归在其他代码中,深度算法,叶子节点个数算法。#include#includeusingnamespacestd;typedefstructtree{chardata;structtree*lchild,*rchild;}tree,*bitree
#include//二叉树的建立,遍历算法(非递归),递归在其他代码中,深度算法,叶子节点个数算法。
#include
#include
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)
{
stackstack;
bitree p=T;
while(p||!stack.empty())
{
if(p!=NULL)
{
stack.push(p);
cout<data;
p=p->lchild;
}
else
{
p=stack.top();
stack.pop();
p=p->rchild;
}
}
}
void inorder(bitree T)
{
stackstack;
bitree p=T;
while(p||!stack.empty())
{
if(p!=NULL)
{
stack.push(p);
p=p->lchild;
}
else
{
p=stack.top();
cout<data;
stack.pop();
p=p->rchild;
}
}
}
void postordertree(bitree T)
{
stackstack;
bitree p=T;
postorder bt;
while(p||!stack.empty())
{
while(p!=NULL)
{
bt=new post;
bt->bit=p;
bt->tag=&#39;L&#39;;
stack.push(bt);
p=p->lchild;
}
while(!stack.empty() && (stack.top())->tag==&#39;R&#39;)
{
bt=stack.top();
stack.pop();
cout<bit->data;
}
if(!stack.empty())
{
bt=stack.top();
bt->tag=&#39;R&#39;;
p=bt->bit;
p=p->rchild;
}
}
}
void levelorder(bitree T)
{
queuequeue;
bitree p=T;
queue.push(p);
while(!queue.empty())
{
p=queue.front();
cout<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<