1.前序,中序,后序遍历递归算法
struct node
{
int data;
struct node *l;
struct node *r;
};
(1)前序
void PreOrderTraverse(struct node *root)
{
if(root==NULL)
{
return;
}
printf("%c",root->data);//注意数据类型
PreOrderTraverse(root->l);
PreOrderTraverse(root->r);
}
(2)中序
void InOrderTraverse(struct node *root)
{
if(root==NULL)
{
return;
}
InOrderTraverse(root->l);
printf("%c",root->data);//注意数据类型
InOrderTraverse(root->r);
}
(3)后序
void PostOrderTraverse(struct node *root)
{
if(root==NULL)
{
return;
}
PostOrderTraverse(root->l);
PostOrderTraverse(root->r);
printf("%c",root->data);//注意数据类型
}
(4)层序
void cengxu(struct node *root)
{
struct node *temp[100];
int in=0,out=0;
temp[in++]=root;
while(in>out)
{
if(temp[out])
{
printf("%c",temp[out]->data);
temp[in++]=temp[out]->l;
temp[in++]=temp[out]->r;
}
out++;
}
}
还原二叉树(递归)
(1)先序中序还原二叉树
struct node
{
int data;
struct node *l;
struct node *r;
};
struct node *creat(int pre[],int In[],int n)
{
if(n==0)
return NULL;
int d,i;
struct node *root;
root=new node;
root->data=pre[0];
for(i=0;i<n;i++)
{
if(In[i]==pre[0])
break;
}
d=i;
root->l=creat(pre+1,In,d);
root->r=creat(pre+d+1,In+d+1,n-d-1);
return root;
};
(2)中序后序还原二叉树
struct node
{
int data;
struct node *l;
struct node *r;
};
struct node *creat(int Post[],int In[],int n)
{
if(n==0)
return NULL;
struct node *root;
root=new node;
root->data=Post[n-1];
int d,i;
for(i=0;i<n;i++)
{
if(In[i]==Post[n-1])
break;
}
d=i;
root->l=creat(Post,In,d);
root->r=creat(Post+d,In+d+1,n-d-1);
return root;
};
应用
(1)后序遍历求树深
int high(struct node *root)
{
if(root)
{
int l,r;
l=high(root->l);
r=high(root->r);
return (l>r?l:r)+1;
}
return 0;
}
(2)统计叶子数
int leaf(struct node *root)
{
if(root==NULL)
return 0;
if(root->l==NULL&&&root->r==NULL)
{
return 1;
}
return leaf(root->l)+leaf(root->r);
}