uva122-树的层次遍历

来源:互联网 发布:刷新快捷键 mac 编辑:程序博客网 时间:2024/06/07 03:15

思路:建树,遍历树。

代码:

#include <bits/stdc++.h>using namespace std;typedef long long ll;const int maxn = 1000 + 20;char s[maxn];bool failed;vector<int> ans;struct Node { bool hv; int v; Node *left, *right; Node():hv(false),left(NULL), right(NULL) { }};Node* root;Node* newnode() { return new Node();}void addnode(int v, char* s){    int len = strlen(s);    Node *u = root;    for (int i=0; i<len; 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->hv) failed = true; // 表示已经赋过值了    u->v = v;    u->hv = true;}bool read_input(){    failed = false;    root = newnode();    while (1) {        if (scanf("%s", s) != 1) return false;        if (!strcmp(s, "()")) break;        int v;        sscanf(&s[1], "%d", &v);        addnode(v, strchr(s, ',')+1);    }    return true;}bool bfs(vector<int>& ans){    queue<Node*> q;    ans.clear();    q.push(root); // 初始一个根节点    while (!q.empty()) {        Node* u = q.front(); q.pop();        if (!u->hv) return false;  //有节点未被赋值        ans.push_back(u->v);  // 增加到输出序列尾部        if (u->left != NULL) q.push(u->left);        if (u->right != NULL) q.push(u->right);    }    return true;}int main(){   int n;   while (read_input()) //输入   {       bfs(ans);    //bfs遍历       if (failed  || !bfs(ans)) puts("not complete");       else {         for (int i=0; i<ans.size(); i++) {            if (i) printf(" "); printf("%d", ans[i]);         }         puts("");       }   }    return 0;}


0 0