#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)
{
Stack q;
q =(Stack)malloc(sizeof(Node));
q->ptr=NULL;
q->link=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 p,t1,t2;
InitStack(&S);
while(*expr!=NULL)
{
if( (*expr<'z') && (*expr>'a'))
{
p=CreateTree(*expr,NULL,NULL);
Push(S,p);
}
else
{
t1=Top(S);
Pop(S);
t2=Top(S);
Pop(S);
p= CreateTree(*expr,t2,t1);
Push(S,p);
}
expr++;
}
return p;
}
void PrintTreeInOrder(Tree T)
{
if(T!=NULL)
{
if(T->LChild!=NULL)
printf("(");
PrintTreeInOrder(T->LChild);
printf("%c", T->info);
PrintTreeInOrder(T->RChild);
if(T->RChild!=NULL )
printf(")");
}
return;
}
void main()
{
char expression[]="abc*+de*f+g*+";
PrintTreeInOrder(ValueTree(expression));
getch();
return;
}
表达式树构建与遍历
本文介绍了一种使用栈来辅助构建表达式树的方法,并实现了中序遍历以输出表达式的功能。通过定义树节点结构及栈操作,程序能够处理输入的字符表达式,创建对应的表达式树。
355

被折叠的 条评论
为什么被折叠?



