基本思想:
无;
关键点:
无;
#include<iostream> #include<stdlib.h> #include<stdio.h> #include<vector> #include<string> #include<math.h> #include<algorithm> #include<cstring> #include<map> #include<queue> using namespace std; struct node { int data; int lchild; int rchild; }; vector<node>tree; vector<int>seq; int st = 0; void layer_find() { queue<int>q; if (tree.size() == 0) return; bool flag = true; q.push(0); while (!q.empty()){ int index = q.front(); if (flag) { cout << tree[index].data; flag = false; } else { cout <<" "<< tree[index].data; } q.pop(); if (tree[index].lchild != -1) q.push(tree[index].lchild); if (tree[index].rchild != -1) q.push(tree[index].rchild); } } void inorder(int n) { if (n == -1) return; inorder(tree[n].lchild); tree[n].data = seq[st++]; inorder(tree[n].rchild); } int main() { int n; cin >> n; tree.resize(n); seq.resize(n); int l, r; for (int i = 0; i < n; i++) { cin >> l >> r; tree[i].lchild = l; tree[i].rchild = r; } for (int i = 0; i < n; i++) { cin >>seq[i]; } sort(seq.begin(), seq.end()); inorder(0); layer_find(); return 0; }
1099 Build A Binary Search Tree (30point(s)) Easy only once *思想雷同1064题目,二叉排序树的构造
原文:https://www.cnblogs.com/songlinxuan/p/12300373.html