用Tree 完成 后序变中序

#include <stdio.h>
#include <conio.h>

typedef struct tn
{
    char info;
    struct tn *lchild;
    struct tn *rchild;

}TreeNode, *Tree;

typedef struct node
{
    Tree ptr;
    struct node *link;
}Node,*Stack;

void InitStack(Stack *p);
void Push(Stack H,Tree x);

void Pop(Stack H);

Tree Top(Stack H);

int EmptyStack(Stack H);

Tree CreateTree(int x, Tree lchild, Tree rchild);/*to create one node of the tree*/

Tree ValueTree(char *expr);/*create the tree according the input*/

void PrintTree(Tree T);/*display the result((a+(b*c))+(((d*e)+f)*g))*/
void main()
{
    char expression[]="abc*+de*f+g*+";
    printf("The postfix is: abc*+de*f+g*+/n");
    printf("After the change, the infix is:/n");
    PrintTree(ValueTree(expression));

    getch();
    return;
}
void InitStack(Stack *p)
{
  Stack q;
  q =(Stack)malloc(sizeof(Node));
  q->link=NULL;
  q->ptr=NULL;
  *p = q;
  return;
}

void Push(Stack H,Tree x)
{
  Stack q;
  q =(Stack)malloc(sizeof(Node));
  q->ptr=x;
  q->link=H->link;
  H->link=q;
  return;

}

void Pop(Stack H)
{
   Stack q;
  q = H->link;
  H->link=H->link->link;
  free(q);
  return;

}
Tree Top(Stack H)
{
   return H->link->ptr;
}

int EmptyStack(Stack H)
{
  if(H->link==NULL)
    return 1;
  else
    return 0;
}
Tree CreateTree(int x, Tree lchild, Tree rchild)
{       Tree T;
        T=(Tree)malloc(sizeof(TreeNode));
        T->info=x;
        T->lchild=lchild;
        T->rchild=rchild;
        return(T);
}

Tree ValueTree(char *expr)
{
    Stack S;
    Tree result;
    Tree ch1,ch2;
    InitStack(&S);
    while(*expr!='/0')
    {
        if(*expr>='a'&& *expr<= 'z')
           { Push(S,CreateTree(*expr,NULL,NULL));   }
        else
        {
            ch1=Top(S);Pop(S);
            ch2=Top(S);Pop(S);
            result=CreateTree(*expr,ch2,ch1);
            Push(S,result);
        }
       expr++;
     }
     return(Top(S));
}
void PrintTree(Tree T)
{
   if(T!=NULL)
   {
    if(T->lchild==NULL&&T->rchild==NULL)
      printf("%c",T->info);
    else
    {
      printf("(");
      PrintTree(T->lchild);
      printf("%c",T->info);
      PrintTree(T->rchild);
      printf(")");
      }

   }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值