#include <iostream>
#include <bits/stdc++.h>
using namespace std;
char pre[55],mid[55],post[55];
int cnt=0;
typedef struct node
{
char data;
node *l,*r;
}Tree;
//根据已知先序遍历建立二叉树(带空结点)
Tree* buildtree_pre()
{
if(pre[cnt]==',')
{
cnt++;
return NULL;
}
Tree *root = new Tree;
root->data=pre[cnt++];
root->l=buildtree_pre();
root->r=buildtree_pre();
return root;
}
//根据先序遍历和中序遍历建立二叉树
Tree* buildtree_pre_mid(int len,char pre[],char mid[])
{
if(!len)
return NULL;
Tree *root = new Tree;
root->data=pre[0];
int i;
for(i=0;i<len;i++)
{
if(mid[i]==pre[0])
break;
}
root->l=buildtree_pre_mid(i,pre+1,mid);
root->r=buildtree_pre_mid(len-i-1,pre+i+1,mid+i+1);
//len-i-1:总长度-左子树-根,是右子树的起点
return root;
}
//根据中序遍历和后序遍历建立二叉树
Tree* buildtree_mid_post(int len,char mid[],char post[])
{
if(!len)
return NULL;
Tree *root = new Tree;
root->data=post[len-1];
int i;
for(i=0;i<len;i++)
{
if(mid[i]==post[len-1])
break;
}
root->l=buildtree_mid_post(i,mid,post);
root->r=buildtree_mid_post(len-i-1,mid+i+1,post+i);
return root;
}
//先序遍历
void pre_Travel(Tree *root)
{
if(root)
{
cout<<root->data;
pre_Travel(root->l);
pre_Travel(root->r);
}
}
//中序遍历
void mid_Travel(Tree *root)
{
if(root)
{
mid_Travel(root->l);
cout<<root->data;
mid_Travel(root->r);
}
}
//后序遍历
void post_Travel(Tree *root)
{
if(root)
{
post_Travel(root->l);
post_Travel(root->r);
cout<<root->data;
}
}
//层序遍历
void Sequence_Travel(Tree *root)
{
queue<Tree *> t;
t.push(root);
while(!t.empty())
{
root=t.front();
t.pop();
if(root)
{
cout<<root->data;
t.push(root->l);
t.push(root->r);
}
}
}
//二叉树的深度
int Deep_Tree(Tree *root)
{
int sum=0,dl,dr;
if(root)
{
dl=Deep_Tree(root->l);
dr=Deep_Tree(root->r);
sum=1+(dl>dr ? dl:dr);
}
return sum;
}
//叶子数目
int Leave_Sum(Tree *root)
{
if(!root)
return 0;
if(!root->l && !root->r)
return 1;
else
return Leave_Sum(root->l) + Leave_Sum(root->r);
}
AA - 二叉树的基本操作代码
最新推荐文章于 2024-09-07 11:07:16 发布