zoukankan      html  css  js  c++  java
  • 二叉树2(动态创建)

    输入一颗二叉树,你的任务是按从上到下、从左到右的顺序输出各个结点的值。每个结点都按照从根结点到它的移动序列给出(L表示左,R表示右)。在输入中,每个结点的左括号和右括号之间没有空格,相邻结点之间用一个空格隔开。每颗树的输入用一对空括号“()”结束(这对括号本身不代表一个结点)。如果从根到某个叶结点的路径上有的结点没有在输入中给出,或者给出超过一次,应当输出-1。

    例如输入:

    (11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()

    输出:

    5 4 8 11 13 4 7 2 1

    输入:

    (3,L)(4,R)()

    输出

    -1

    #include"iostream"
    #include"queue"
    using namespace std;
    typedef int element;
    class Tree{
    private:
        element data;
        Tree *left;
        Tree *right;
    public:
        Tree(element data = 0){
            this->data = data;
            left = NULL;
            right = NULL;
        }
        void showsq(){
            queue<Tree*> q;
            q.push(this);
            while(!q.empty()){
                Tree *p = q.front();
                cout<<p->data<<ends;
                if(p->left){
                    q.push(p->left);
                }
                if(p->right){
                    q.push(p->right);
                }
                q.pop();
            }
        }
        void dynamicCreate(Tree* &t,int data,char *pos,int i = 0){
            if(!t){
                t = new Tree();
            }
            if(pos[i] == ')'){
                t->data = data;
            }
            else if(pos[i] == 'L'){
                dynamicCreate(t->left,data,pos,i + 1);
            }
            else if(pos[i] == 'R'){
                dynamicCreate(t->right,data,pos,i + 1);
            }
            else{
                return ;
            }
        }
    };
    
    int main(){
        void pickup(char *s,int &data,char* position);        
        Tree *t = NULL;
        int data;
        char position[20],str[50];
        while(true){
            cin>>str;
            if(str[1] == ')'){
                break;
            }
            pickup(str,data,position);        //提取信息
            t->dynamicCreate(t,data,position);
        }
        t->showsq();
        return 0;
    }
    
    void pickup(char *s,int &data,char* position){
            data = atoi(&s[1]);
            char *pos = strchr(s,',') + 1;
            strcpy(position,pos);
    }
    //(11,LL) (7,LLL) (8,R) (5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) ()
    //(11,LL) (7,LLL) (8,R)
    //(12,R) (2,LLR) ()
  • 相关阅读:
    spring中各个模块的作用
    《Spring实战》学习笔记-第四章:面向切面的Spring
    《Spring实战》学习笔记-第四章:面向切面的Spring
    Centos7下永久修改mysql5.6最大连接数
    Prefix-List
    Route-Map
    PBR Lab2
    Lab PBR
    ISIS超载位解决流量黑洞
    ISIS TLV
  • 原文地址:https://www.cnblogs.com/oleolema/p/9028439.html
Copyright © 2011-2022 走看看