二叉树的操作

#include <iostream>
#include <string>
using namespace std;


#include <stack>
#include <queue>
/*
二叉树的 : 
建立
先序遍历
中序遍历
后序遍历
层次遍历
二叉树的深度
二叉树的宽度
*/
struct BiNode
{
int data;
BiNode *left,*right;
};


void create(BiNode *&T)
{
int i;
cin>>i;
if(i==0)
T=0;
else
{
T=new BiNode;
T->data=i;
create(T->left);
create(T->right);
}
}
//先序遍历 递归
void preorder(BiNode *T)
{
if(T==NULL)
return;
cout<<T->data<<' ';
preorder(T->left);
preorder(T->right);
}
//中序遍历 递归
void inorder(BiNode *T)
{
if(T==0)
return;
inorder(T->left);
cout<<T->data<<' ';
inorder(T->right);
}
//后序遍历 递归
void postorder(BiNode *T)
{
if(T==NULL)
return;
postorder(T->left);
postorder(T->right);
cout<<T->data<<' ';
}
//先序遍历
void pre(BiNode *T)
{
if(T==NULL)
return;
stack<BiNode *> st;
BiNode *p=T;
while(! (p==0 && st.empty()))
{
while(p!=NULL)
{
cout<<p->data<<' ';
st.push(p);
if(p->left)
{
p=p->left;
}
else 
{
st.pop();
p=p->right;
}

}
if(!st.empty())
{
p=st.top()->right;
st.pop();
}
}
}
//中序遍历
void mid(BiNode *T)
{
if(T==0)
return;
stack<BiNode *> st;
BiNode *p=T;
while(p!=0 || !st.empty())
{
while(p!=0)
{
st.push(p);
p=p->left;
}
if( !st.empty() )
{
cout<<st.top()<<' ';
p=st.top()->right;
st.pop();
}
}
}
//层次遍历
void level(BiNode *T)
{
if(T==0)
return;
queue<BiNode *> q;
BiNode *p=T;
q.push(p);
while(!q.empty())
{
p=q.front();
cout<<p->data<<' ';
if(p->left)
q.push(p->left);
if(p->right)
q.push(p->right);
q.pop();
}
}


int depth(BiNode *T)
{
if(T==NULL)
return 0;


return (depth(T->left)>depth(T->right)?depth(T->left):depth(T->right))+1;


}


int width(BiNode *T)
{
if(T==0)
return 0;
int max=1,tmp=0;
BiNode *p=T;
queue<BiNode *> q;
q.push(p);
int k=1;//用来记录当前节点的叶子数
while(!q.empty())
{

while(k>0)
{
p=q.front();
q.pop();
if(p->left)
{
q.push(p->left);
tmp++;
}
if(p->right)
{
q.push(p->right);
tmp++;
}


if(max<tmp)
{
max=tmp;
}
k--;
}

{
k=tmp;
tmp=0;
}
}
return max;
}






/*
Description  
         给定一个二叉树,获取该二叉树的宽度深度。
Prototype
         int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight)
Input Param 
         head   需要获取深度的二叉树头结点
Output Param 
         pulWidth   宽度
         pulHeight  高度
Return Value
         0          成功
         1          失败或其他异常
*/
int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight)
{
/*在这里实现功能*/
if(&head==0)
    {
*pulWidth=0;
*pulHeight=0;
return 1;
}
*pulWidth=width(&head);
*pulHeight=depth(&head);
return 0;
}


void main()
{
while(1)
{
BiNode *T=0;
create(T);
unsigned int deep=0;
unsigned int  wide=0;
GetBiNodeInfo(*T, &wide,&deep);
cout<<"depth="<<deep<<endl;
cout<<"width="<<wide<<endl;
cout<<"--------------------"<<endl;


}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值