PAT-1099-Build A Binary Search T

2016-03-11  本文已影响96人  鬼谷神奇

https://www.patest.cn/contests/pat-a-practise/1099

#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>

using namespace std;

struct Node{
    int no, value;
    Node * left, * right;
};

int buf[505];
Node Tree[505];
int size = 0;
queue<Node *> qu;

void inOrder(Node * root)
{
    if(root != NULL)
    {
        inOrder(root->left);
        root->value = buf[size++];
        inOrder(root->right);
    }
}

void levelOrder(Node root, int n)
{
    while(!qu.empty())
        qu.pop();

    qu.push(&root);

    int cnt = 0;
    while(!qu.empty())
    {
        Node * tmp = qu.front();
        qu.pop();
        cnt++;
        cout << tmp->value << (cnt < n ? " " : "");

        if(tmp->left != NULL)
            qu.push(tmp->left);
        if(tmp->right != NULL)
            qu.push(tmp->right);
    }

}

int main()
{
    ifstream cin("in.txt");

    int n;

    while(cin >> n)
    {
        for(int i = 0; i < n; ++i)
        {
            Tree[i].no = i;
            Tree[i].value = 0;
            Tree[i].left = Tree[i].right = NULL;
        }
        for(int i = 0; i < n; ++i)
        {
            int a, b;
            cin >> a >> b;

            if(a != -1)
                Tree[i].left = &Tree[a];
            else
                Tree[i].left = NULL;
            
            if(b != -1)
                Tree[i].right = &Tree[b];
            else
                Tree[i].right = NULL;
        }

        for(int i = 0; i < n; ++i)
            cin >> buf[i];
        sort(buf, buf+n);
        inOrder(&Tree[0]);

        levelOrder(Tree[0], n);
    }
}
上一篇下一篇

猜你喜欢

热点阅读