树形问题_汇总

表达式树
#define maxn 1000
int lch[maxn],rch[maxn],char op[maxn];//数组表示树形结构
int nc=0;//结点序号
int build_tree(char *s,int x,int y)
{
int i,c1=-1,c2=-1,p=0;
int u;
if(y-x==1)
{
u=++nc;
lch[u]=rch[u]=0;
op[u]=s[x];
return u;
}
for(i=x;i<y;i++)
{
switch(s[i])
{
case'(':p++;break;//通过p判断优先级最低的运算符
case')':p--;break;
case'+':case'-':if(!p)c1=i;break;
case'*':case'/':if(!p)c2=i;break;
}
}
if(c1<0)
c1=c2;
if(c1<0)
return build_tree(s,x+1,y-1);
u=++nc;
lch[u]=build_tree(s,x,c1);
rch[u]=build_tree(s,c1+1,y);
op[u]=s[c1];
return u;
}
        由先序,中序遍历求深度遍历
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int n;
char s1[1005],s2[1005];
typedef struct node//定义树的结构体
{
     char data;
     int index;
     struct node *lchild,*rchild;//左右孩子表示法
}Bitree,*Tree;
struct node *queue[1000];//指针队列,储存了每个节点的地址
void dfs(Tree &root, int index)//深搜查找树的节点,通过先序,中序遍历的特点,得出答案
{
     if (root==NULL)
     {
         root=(Tree) malloc ( sizeof (Bitree));
         root->data=s2[index];
         root->index=index;
         root->lchild=NULL;
         root->rchild=NULL;
         return ;
     }
     else
     {
         if (index<root->index)
             dfs(root->lchild,index);
         else
             dfs(root->rchild,index);
     }
}
void creatbitree(Tree &root, int n)
{
     int i,j,index;
     root=(Tree) malloc ( sizeof (Bitree));//分配内存,结构体内有指针必须如此处理
     for (i=0;i<n;i++)
         if (s2[i]==s1[0])
         {
             root->data=s1[0];
             root->index=i;
             root->lchild=NULL;
             root->rchild=NULL;
             break ;
         }
     index=i;
     for (i=1;i<n;i++)
         for (j=0;j<n;j++)
             if (s2[j]==s1[i])
             {
                 if (j<index)
                     dfs(root->lchild,j);
                 else
                     dfs(root->rchild,j);
                 break ;
             }
}
int main()
{
     int m;
     int s,t;
     Tree root;
     struct node *u;
     scanf ( "%d" ,&m);
     while (m--)
     {
         root=NULL;//初始化根节点,切记
         s=t=0;
         scanf ( "%s%s" ,s1,s2);
         n= strlen (s1);
         creatbitree(root,n);
         queue[t++]=root;//队列实现深度,广度跟先序遍历同构
         while (s<t)
         {
             u=queue[s++];
             if (u!=NULL)
             {
                 if (u->lchild!=NULL)
                     queue[t++]=u->lchild;
                 if (u->rchild!=NULL)
                     queue[t++]=u->rchild;
             }
         }
         for (s=0;s<t;s++)
             printf ( "%c" ,queue[s]->data);
         printf ( "\n" );
     }
     return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值