求解:一个二叉树的C语言程序

来源:百度知道 编辑:UC知道 时间:2024/06/10 05:14:36
求解:一个二叉树的C语言程序
用C编
表达式转换 问题描述:
写一个程序,根据输入的算术表达式构造对应的二叉树 基本要求:
(1)以字符形式输入语法正确的常规表达式;
(2)根据表达式构造对应的二叉树;
(3)利用二叉树的非递归算法输出常规表达式对应的前缀表达式;
(4)利用二叉树的非递归算法输出常规表达式对应的后缀表达式;
拜托大家了啊!

#include <stdio.h>
#include <malloc.h>
#define maxsize 1024
#define null 0
struct node
{int data;
struct node *lchild, *rchild;
};
struct node *root;

struct node *CREATREE()
{char ch;
struct node *Q[maxsize];
int front,rear;
struct node *root,*s;
root=null;
front=1;rear=0;
while((ch=getchar())!='#')
{s=null;
if(ch!=' ')
{s=malloc(sizeof(struct node));
s->data=ch;
s->lchild=null;
s->rchild=null;
}
rear++;
Q[rear]=s;
if(rear==1) root=s;
else
{if((s!=null)&&(Q[front]!=null))
if(rear%2==0) Q[front]->lchild=s;
else Q[front]->rchild=s;
if(rear%2==1) front++;
}
}
return root;
}
void preorder(struct node *p)
{if(p!=null)
{printf("%c",p->data);
preorder(p->lchild);
preorder(p->rchild);}