根据后缀表达式构建一个二叉树,其前序遍历就是它的前缀表达式
建树:从后缀表达式最后一位往前建
#include <string.h>
#include <stdlib.h>
#include <iostream>
typedef struct btnode
{
char data;
struct btnode *lchild;
struct btnode *rchild;
}btnode;
char A[]="abc*+def/*/";
int n=strlen(A)-1;
int judge(char a)
{
switch(a)
{
case '+':return 1;
case '-':return 1;
case '*':return 1;
case '/':return 1;
default :return 0;
}
}
btnode* fun()
{
btnode *bt=(btnode *)malloc(sizeof(btnode));
bt->data=A[n];
if(n<0) return NULL;
else if(judge(A[n])==0)
{
bt->lchild=bt->rchild=NULL;
}
else
{
n--;
bt->rchild=fun();
n--;
bt->lchild=fun();
}
return bt;
}
void pre_order(btnode *bt)
{
if(bt)
{
printf("%c",bt->data);
pre_order(bt->lchild);
pre_order(bt->rchild);
}
}
int main()
{
btnode *bt;
bt=fun();
pre_order(bt);
return 0;
}