A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right. Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST. Input Specification:Each input file contains one test case. For each case, the first line contains a positive integer N (≤). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are 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 be separated by a space, and there must be no extra space at the end of the line. Sample Input:
Sample Output:
通过观察可以注意到,对完全二叉树当中的任何一个结点(设编号为x),其左孩子的编号一定是2x,而右孩子的编号一定是2x 1。也就是说,完全二叉树可以通过建立一个大小为2k的数组来存放所有结点的信息,其中k为完全二叉树的最大高度,且1号位存放的必须是根结点(想一想为什么根结点不能存在下标为0处?)。这样就可以用数组的下标来表图95完全二又树编号示意示结点编号,且左孩子和右孩子的编号都可以直接计算得到。
1 #include <iostream> 2 #include <vector> 3 #include <algorithm> 4 using namespace std; 5 int N, nums[1001], res[1001], index = 0; 6 void levelOrder(int k) 7 { 8 if (k > N)//叶子节点 9 return; 10 levelOrder(k * 2);//遍历左子树 11 res[k] = nums[index ];//即遍历完左子树后,此时即为根节点 12 levelOrder(k * 2 1);//遍历右子树 13 } 14 int main() 15 { 16 cin >> N; 17 for (int i = 0; i < N; i) 18 cin >> nums[i]; 19 sort(nums, nums N, [](int a, int b) {return a < b; }); 20 levelOrder(1); 21 for (int i = 1; i <= N; i) 22 cout << res[i] << (i == N ? "" : " "); 23 return 0; 24 } 来源:https://www./content-4-375901.html |
|