1099. Build A Binary Search Tree (30)

来源:互联网 发布:台湾传奇网络 编辑:程序博客网 时间:2024/06/07 03:36

先构建树的模型,再对模型的节点赋值,最后bfs输出

#include<iostream>#include<vector>#include<algorithm>#include<deque>using namespace std;struct node {    int data;    node *l, *r;};int N;vector<node> all;vector<int> da;int cnt = 0;void Inorder(node *&root)//中序输入{    if (root == NULL) return;    Inorder(root->l);    root->data=da[cnt++];    Inorder(root->r);}int main(){    cin >> N;    if (N <= 0) exit(0);    all.resize(N);    da.resize(N);    for (int t = 0;t < N;t++)//构建树    {        int a, b;        cin >> a >> b;        if (a != -1) all[t].l = &all[a];        else all[t].l = NULL;        if (b != -1) all[t].r = &all[b];        else all[t].r = NULL;    }    for (int t = 0;t < N;t++)        cin >> da[t];    sort(da.begin(), da.end());//对数据排序    node *root = &all[0];    Inorder(root);    root= &all[0];    cout << root->data;    deque<node *> x;    if (root->l) x.push_back(root->l);    if (root->r) x.push_back(root->r);    while (!x.empty())//广度遍历    {        node * tem = x.front();        x.pop_front();        cout << " " << tem->data;        if (tem->l) x.push_back(tem->l);        if (tem->r) x.push_back(tem->r);    }    cout << endl;}
0 0
原创粉丝点击