The topics are as follows:
A binary Search Tree (BST) is recursively defined as a Binary Tree which have the following properties:
- The left subtree of a node contains only nodes with keys less than the node ' s key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node ' s key.
- Both the left and right subtrees must also is binary search trees.
A complete Binary tree (CBT) was a tree that was completely filled, with the possible exception of the bottom level, which I s filled from left to right.
Now given a sequence of distinct non-negative integer keys, a unique BST can being constructed if it is required that the Tre E must also be a CBT. You is supposed to output the level order traversal sequence of this BST.
Input Specification:
Each input file contains the one test case. For each case, the first line contains a positive integer N (<=1000). Then N distinct non-negative integer keys is given in the next line. All the numbers in a line is separated by a space and is no greater than 2000.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must is separated by a space, and there must is no extra space at the end of the line.
Sample Input:
101 2 3 4 5 6 7 8 9 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
The topic requires a complete binary search tree for a given sequence, and the so-called complete binary search tree is the search tree that satisfies the complete binary tree.
We know that the node I of a complete binary tree is numbered from 1, then the left son is 2*i and the right son is 2*i+1, while the middle order of the binary search tree is ascending, so only the input sequence is sorted in ascending order, then the complete binary tree is sequentially traversed, and the corresponding elements are filled in.
#include <iostream> #include <vector> #include <stdio.h> #include <algorithm>using namespace std;vector<int> tree;vector<int> nodes;int n;void buildtree (int root) { static int index = 1; if (Root > N) return; Buildtree (root * 2); Tree[root] = nodes[index++]; Buildtree (Root * 2 + 1);} int main () { cin >> N; Nodes.resize (n+1); Tree.resize (n+1); for (int i = 1; I <= N; i++) { scanf ("%d", &nodes[i]); } Sort (Nodes.begin (), Nodes.end ()); Buildtree (1); printf ("%d", tree[1]); for (int i = 2; I <= N; i++) printf ("%d", Tree[i]); cout << Endl; return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
1064. Complete Binary Search Tree (30)