zoukankan      html  css  js  c++  java
  • 后缀表达式 遍历二叉树



    //根据后缀表达式建立二叉树
    #include <iostream>
    #include<stack>
    #include<string>
    using namespace std;
    class Note
    {
    public:
        char d;
        Note *Lchild;
        Note *Rchild;
        Note()
        {
            Lchild=NULL;
            Rchild=NULL;
        }
    };
    
    stack<Note *> sta;
    string data;
    void make_tree(char a)
    {
        Note *t;
        if(a>='0'&&a<='9')
        {
            t=new Note;
            t->d=a;
            sta.push(t);
        }
        else
        {
            t=new Note;
            t->d=a;
            t->Rchild=sta.top();
            sta.pop();
            t->Lchild=sta.top();
            sta.pop();
            sta.push(t);
        }
    }
    bool print(char e)
    {
        cout<<e;
        return true;
    }
    bool print_tree(Note *head,bool (*visit)(char e))
    {
        if(head)
        {
            if(visit(head->d))
                if(print_tree(head->Lchild,print))
                    if(print_tree(head->Rchild,print))
                        return true;
            return false;
        }
        else
            return true;
    }
    bool delete_tree(Note *head)
    {
        if(head)
        {
            if(delete_tree(head->Lchild))
                return true;
            else
            {
                delete head;
                return false;
            }
            if(delete_tree(head->Rchild))
                  return true;
            else
            {
                delete head;
                return false;
            }
            delete head;
        }
    
        return true;
    }
    int main()
    {
    
        cin>>data;
        Note *head;
        for(unsigned int i=0;i<data.length();i++)
        {
            make_tree(data[i]);
        }
        head=sta.top();
        sta.pop();
        print_tree(head,print);
        delete_tree(head);
    
    
        return 0;
    }


  • 相关阅读:
    NOIP前的一些计划
    回文自动机[学习笔记]
    Luogu-3705 [SDOI2017]新生舞会
    01分数规划[学习笔记]
    jvm参数总结
    读懂jstack
    PRODUCER配置加载
    为什么WAIT必须在同步块中
    NIO学习笔记
    dp求最长递增子序列并输出
  • 原文地址:https://www.cnblogs.com/frankM/p/4399481.html
Copyright © 2011-2022 走看看