Trees on the level

 

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<queue>
#include<vector>
#include<cstring>
using namespace std;
struct Node
{
    bool have_value;
    int v;
    Node* left;
    Node* right;
    Node() :have_value(false), left(NULL), right(NULL) {}
};
Node* root;
bool failed;

Node* newnode() { return new Node(); }

void insertnode(int v, char s[])
{
    Node* u = root;
    int n = strlen(s);
    for (int i = 0; i < n; i++)
    {
        if (s[i] == 'L')
        {
            if (u->left == NULL) u->left = newnode();
            u = u->left;
        }
        if (s[i] == 'R')
        {
            if (u->right == NULL) u->right = newnode();
            u = u->right;
        }
    }
    if (u->have_value) failed = true;
    u->v = v;
    u->have_value = true;
}
bool read_input()
{
    failed = false;
    char s[100000];
    root = newnode();
    int q = 0;
    while (scanf("%s", s) == 1 && strcmp(s, "()"))
    {
        q = 1;
        int v;
        sscanf(&s[1], "%d", &v);//第一个相当于在屏幕上输入,第二个是输入的格式,第三个是目标赋值
        insertnode(v, strchr(s, ',') + 1);//将编号和二叉树的位置传入,然后该函数会将编号插入二叉树
    }
    if (q)
        return true;
    else
        return false;
}

bool bfs(vector<int>& mm)//遍历函数,利用队列进行
{
    mm.clear();
    queue<Node*> per;
    per.push(root);
    while (!per.empty())
    {
        Node* u = per.front();
        per.pop();
        if (!u->have_value)return false;
        mm.push_back(u->v);
        if (u->left != NULL)per.push(u->left);
        if (u->right != NULL)per.push(u->right);
    }
    return true;
}

int main(void)
{
    vector<int> mm;
    while (read_input())
    {
        if (bfs(mm) && !failed)
        {
            for (vector<int>::iterator it = mm.begin(); it != mm.end(); it++)
            {
                if (it != mm.begin())printf(" ");
                printf("%d", *it);
            }
            cout << endl;
        }
        else
            cout << "not complete" << endl;
    }
    return 0;
}

 

posted @ 2021-02-06 20:54  loliconsk  阅读(75)  评论(0)    收藏  举报