数据结构与算法(c)--第4章

4.2.2 构造一棵表达式树
代码如下:

#include <iostream>
#include <string>
#include <sstream>
#include <stack>
using namespace std;

typedef char ELEMENT;
typedef struct TreeNode
{
    ELEMENT vlaue;
    struct TreeNode *lchild;
    struct TreeNode *rchild;
}*Bitree;

/*
    中序遍历
*/
void infix_view(Bitree);

int main()
{
    string str;
    cin >> str;
    istringstream istream(str); //string流,内存IO,定义后直接初始化
    char word;
    stack<Bitree> m_stack;
    while (istream >> word){  //当遇到结束符时,流错误,退出while
        if (word == '+' || word == '-' || word == '*' || word == '/'){
            Bitree p;
            p = (Bitree)malloc(sizeof(TreeNode));
            p->vlaue = word;
            p->rchild = m_stack.top(); //返回栈顶元素,但不将元素弹栈
            m_stack.pop();//弹出栈顶元素,但不返回值
            p->lchild = m_stack.top();
            m_stack.pop();
            m_stack.push(p);
        }
        else{
            Bitree q;
            q = (Bitree)malloc(sizeof(TreeNode));
            q->vlaue = word;
            q->lchild = NULL;
            q->rchild = NULL;
            m_stack.push(q);
        }
    }
    Bitree root = m_stack.top();
    m_stack.pop();
    infix_view(root);
    cout << endl;
    // 注意,malloc 后应该 free 释放树
    system("pause");
}

void infix_view(Bitree tree)
{
    if (tree){
        if (tree->lchild)infix_view(tree->lchild);
        cout << tree->vlaue;
        if (tree->rchild)infix_view(tree->rchild);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值