1064. Complete Binary Search Tree (30)

Source: Internet
Author: User
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 ");}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.