A column of numbers can be provided to form a fully binary search tree, which is used for layered traversal of a fully Binary Search Tree.
Idea: the process of building a tree can be seen as a process of constantly searching for child root nodes.
Based on the full Binary Tree feature, you can determine the corresponding root node subscript by determining the number of child nodes in the left subtree.
Recursive build.
Code:
# Include <iostream> # include <vector> # include <cmath> # include <algorithm> # include <fstream> using namespace STD; vector <int> nodes; /** @ parm L, R point for nodes @ parm trees store constructed CBT @ parm POS position for trees */void buildcbt (int l, int R, const vector <int> & nodes, vector <int> & trees, int POS) {If (L> r) return; If (L = r) {trees [POS] = nodes [l];} else {int sumnode = r-L + 1; int level = Log (double) sumnode)/log (double) 2) + 1; int lastlevelnodes = POW (double) 2, level-1); int knodes = lastLevelNodes-1; // remove the number of nodes in the last row int lastrealnodes = sumnode-knodes; int offset = 0; If (lastrealnodes> = lastlevelnodes/2) {offset = lastlevelnodes/2;} else {offset = lastrealnodes;} int nodeindex = L + knodes/2 + offset; // cout <"nodeindex" <nodeindex <"" <Endl; trees [POS] = nodes [nodeindex]; // cout <"trees [POS]" <trees [POS] <""; buildcbt (L, nodeIndex-1, nodes, trees, 2 * POS ); buildcbt (nodeindex + 1, R, nodes, trees, 2 * POS + 1) ;}} int main () {ifstream CIN ("data.txt"); int num; cin> num; int K; For (INT I = 0; I <num; ++ I) {CIN> K; nodes. push_back (k);} vector <int> trees (Num + 1); sort (nodes. begin (), nodes. end (); buildcbt (0, num-1, nodes, trees, 1); For (INT I = 1; I <trees. size ()-1; ++ I) {cout <trees [I] <"" ;}cout <trees [trees. size ()-1] <"\ n"; // system ("pause ");}