1064 Complete Binary Search Tree (30) – 有意思的另一道题
A Binary Search Tree (BST) is recursively defined as a binary tree which has 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 be binary search trees.
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 (<=1000). 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:
10
1 2 3 4 5 6 7 8 9 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
大致题意为:给出一串数字,输出由这串数字所组成的完全二次搜索树的层序遍历。
首先必须了解什么是完全二叉搜索树。
- 满足二叉搜索树的性质:左子树的所有值小于根节点,右子树的所有值大于根节点。
- 满足完全二叉树的性质:详见百度。注意完全二叉树和满二叉树的区别。
分析:
法一:
- 按照正常思维,第一步是去找根节点,由于需要满足完全二叉树的性质,根节点的下标可以总结确定。
- 在推导的过程中可以得出结论,所得完全二叉树的中序遍历序列一定等于原数字串的从小到大排列,可以亲手写几个试试,不予证明。
- 所以知道了中序遍历序列和确定根节点下标的方法,可以建树。
法二:
老规矩好方法写在后面:以法一的做法,代码50行往上数。然而刷题一定要有看别人代码的习惯,此题百度的第一个便给出精妙的解法。
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
vector<int> input;
vector<int> output;
int n, Index = 0;
void inorder(int root) //中序遍历
{
if (root > n)return;
inorder(root * 2); // L
output[root] = input[Index++]; // D
inorder(root * 2 + 1); // R
}
int main() {
int t;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> t;
input.push_back(t);
}
output.resize(n + 1);
sort(input.begin(), input.end());
inorder(1);
cout << output[1];
for (int i = 2; i <= n; i++)cout << " " << output[i];
return 0;
}
- 利用树状数组,直接用中序遍历开始建树,代码中inorder()函数其实是在建树。由于具有完全二叉树的性质,这样建树刚好符合要求。代码简洁易懂,惊为天人,钦佩原作。