uva122_二叉樹的層次歷遍

大白2,P150頁

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

bool failed = false;
Node* root;
vector<int> ans;

void addnode(int v,char*s);
Node* newnode(){return new Node;}
bool bfs(vector<int>& res);

int main()
{
    while(1)
    {
        failed = false;
        char s[N];
        root = newnode();
        while(1)
        {
            if(scanf("%s",s) !=1) return 0;
            if(!strcmp(s,"()"))      break;
            int v;
            sscanf(&s[1],"%d",&v);
            addnode(v,strchr(s,',')+1);
        }
        bfs(ans);
        if(!root->have_value) failed = true;
        if(!failed)
        {
            for(int i = 0 ; i <= ans.size()-1 ; i++)
            {
                if(i!=0)            printf(" ");
                printf("%d",ans[i]);
            }
            puts("");
        }
        else
            puts("not complete");
    }
}

void addnode(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;
        }
        else 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 bfs(vector<int>& ans)
{
    ans.clear();
    queue<Node*> q;
    q.push(root);

    while(!q.empty())
    {
        Node* temp = q.front();q.pop();

        if(!temp->have_value) return false;
        if(temp->left != NULL)     q.push(temp->left);
        if(temp->right != NULL)     q.push(temp->right);
        ans.push_back(temp->v);
    }
    return true;
}

發佈了50 篇原創文章 · 獲贊 9 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章