1099. Build A Binary Search Tree (30)

BST的中序遍历是从小到大排列的,所以就这么做好了。。。

#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<algorithm>
#include<queue>
#include<set>
#include<stack>
using namespace std;
const int inf = 99999999;

struct node {
  int val;
  int l, r;

};
node arr[105];
int k = 0;
int c = 0;
int numbers[105];

void inorder(int root) {
  if (root == -1) {
    return;
  }
  inorder(arr[root].l);
  arr[root].val = numbers[k];
  k++;
  inorder(arr[root].r);
}

void bfs(int root) {
  queue<int> q;
  q.push(root);
  while (!q.empty()) {
    int temp = q.front();
    q.pop();
    if (c != 0) {
      cout <<' '<<arr[temp].val;
    }
    else {
      c++;
      cout << arr[temp].val;
    }
    if (arr[temp].l != -1) {
      q.push(arr[temp].l);
    }
    if (arr[temp].r != -1) {
      q.push(arr[temp].r);
    }
  }
}

int main() {
  int num;
  cin >> num;
  

  for (int i = 0; i < num; i++) {
    arr[i].val = i;
    int n1, n2;
    cin >> n1 >> n2;
    arr[i].l = n1;
    arr[i].r = n2;
  }

  
  for (int i = 0; i < num; i++) {
    int n;
    cin >> n;
    numbers[i] = n;
  }
  sort(numbers, numbers + num);
  inorder(0);

  bfs(0);

  system("pause");
}

 

posted on 2017-08-29 16:44  wsggb123  阅读(83)  评论(0)    收藏  举报

导航