1099. Build A Binary Search Tree (30)

题目地址:http://www.patest.cn/contests/pat-a-practise/1099

搜索二叉树的建立与遍历,比较简单,采用合适的c++stl写很快

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <unordered_map>
#include <algorithm>

using namespace std;

#define N 102
int n;

struct mydata{
  int no;
  int left;
  int right;
};

mydata a[N];

typedef struct node{
  int data;
  struct node* left;
  struct node* right;
  node(int _data = -1){
    data = _data;
    left = NULL;
    right = NULL;
  }
}Bnode;


Bnode* createTree(Bnode* root,int num)
{
  root = new node(num);
  if (a[num].left == -1){
    root->left = NULL;
  }
  else{
    root->left = createTree(root->left, a[num].left);
  }
  if (a[num].right == -1){
    root->right = NULL;
  }
  else{
    root->right = createTree(root->right, a[num].right);
  }
  return root;
}

Bnode* root;

vector<int> inSq;

void inorder(Bnode* root)
{
  if (root != NULL)
  {
    inorder(root->left);
    inSq.push_back(root->data);
    inorder(root->right);
  }
}


bool cmp(int x, int y)
{
  return x < y;
}

int main()
{
  //freopen("in", "r", stdin);
  scanf("%d", &n);
  int i;
  for (i = 0; i < n; i++)
  {
    scanf("%d%d", &a[i].left, &a[i].right);
    a[i].no = i;
  }
  root = NULL;
  root = createTree(root, 0);

  inorder(root);

  int v[N];
  for (i = 0; i < n; i++)
  {
    scanf("%d", &v[i]);
  }
  sort(v, v + n, cmp);
  unordered_map<int, int> um;
  for (i = 0; i < n; i++)
  {
    um[inSq[i]] = v[i];
  }

  vector<int> ans;
  //
  queue<Bnode*> que;
  que.push(root);
  while ( !que.empty())
  {
    Bnode* bt = que.front();
    que.pop();
    ans.push_back(um[bt->data]);
    if (bt->left != NULL)
    {
      que.push(bt->left);
    }
    if (bt->right != NULL)
    {
      que.push(bt->right);
    }
  }
  printf("%d", ans[0]);
  for (i = 1; i < n; i++)
  {
    printf(" %d", ans[i]);
  }
  printf("\n");
  return 0;
}

你可能感兴趣的:(1099. Build A Binary Search Tree (30))