数据结构:表达式树

来源:互联网 发布:java扫描局域网内主机 编辑:程序博客网 时间:2024/05/15 07:20

摘要:
(1)表达式树的树叶是操作数。其他节点为操作符。
这里写图片描述
(2)通过递归产生一个带括号的左表达式,然后打出根的操作符号,再递归的产生右表达式。这是一种中缀表达(也是中序遍历)
(3)另一种方式是进行后序遍历,产生一个后缀表达式。
(4)现在给出一种教材上的构造表达式树的算法:
【1】首先输入一个后缀表达式(如果不是需要转换)
【2】依次读入元素,如果是操作数,则建立一个单节点树,并将指向它的指针压入栈。如果是操作符,就栈中弹出两棵树并将该操作符作为一个新的根,两棵树分别为左右儿子。然后将这个新的树压入栈。
代码如下

#include "stdafx.h"#include "stdlib.h"#include "malloc.h"#define EmptyTos -1typedef struct StackRecord *Stack;typedef struct TreeRecord *tree;struct TreeRecord{    char Element;    tree Left;    tree Right;};struct StackRecord{    int Cpapcity;    int TopStack;    tree *Array;};Stack Create(int MaxElements){    Stack S;    S = (Stack)malloc(sizeof(StackRecord));    S->Array = (tree *)malloc(sizeof(tree)*MaxElements);    S->TopStack = -1;    S->Cpapcity = MaxElements;    return S;}void Push(Stack S,tree X){    if(S->TopStack >= S->Cpapcity-1)    {        puts("cannot push an elements into a full stack");        return;    }    else        S->Array[++S->TopStack] = X;}tree Pop(Stack S){    if (S->TopStack == EmptyTos)    {        puts("cannot Pop an empty stack");        exit(-1);    }    else        return(S->Array[S->TopStack --]);}tree Create_tree(char Element,tree Left,tree Right){    tree T;    T = (tree)malloc(sizeof(TreeRecord));    T->Element = Element;    T->Left = Left;    T->Right = Right;    return T;};tree Create_expression (Stack S,char *A){    int i = 0;    tree temp1,temp2;    tree T;    tree T1,T2;    while(A[i] != '\0')    {        if (A[i]<='9'&&A[i]>='0')        {               T1 = Create_tree(A[i++],NULL,NULL);            Push(S,T1);        }          else        {            temp1 = Pop(S);            temp2 = Pop(S);            T = Create_tree(A[i++],temp2,temp1);            Push(S,T);        }    }    return T;}int _tmain(int argc, _TCHAR* argv[]){    char A[100] = {0};    tree T;    Stack S;    puts("please input the expression:");    scanf("%s",A);    S = Create(20);    T = Create_expression(S,A);    return 0;}
0 0
原创粉丝点击