表达式树C/C++

#include <bits/stdc++.h>
using namespace std;
typedef char Element;
struct Node;
typedef struct Node *BTree;
struct Node{
    Element data;
    struct Node *lchild;
    struct Node *rchild;
}; 

bool IsOperator(char ch)
{
    if(ch=='+' || ch=='-' || ch=='*' || ch=='/')
        return true;
    return false;
}

BTree NewNode(Element x)
{
    BTree p=(BTree)malloc(sizeof(struct Node));
    p->data=x;
    p->lchild=NULL;
    p->rchild=NULL;
    return p; 
}

BTree Create(char t[])
{
    stack <BTree> s;
    BTree p;
    for(int i=0;t[i]!='\0';i++){
        p=NewNode(t[i]);
        if(IsOperator(t[i])){
            p->rchild=s.top();
            s.pop();
            p->lchild=s.top();
            s.pop();
        }
        s.push(p);
    }
    p=s.top();
    return p;    

void Pre_Order(BTree root)
{
    if(root==NULL)
        return ;
    printf("%c",root->data);
    Pre_Order(root->lchild);
    Pre_Order(root->rchild);
}

int main()
{
    char t[1000];
    gets(t);
    BTree root=Create(t);
//    Pre_Order(root);     加一个先序遍历验证 
    return 0;
}

猜你喜欢

转载自blog.csdn.net/linyuan703/article/details/81225052