1064. Complete Binary Search Tree (30)

分析:

  考察BST + 完全二叉树的性质,注意:

    (1):先用排序排好,然后由于是完全二叉树,我们使用中序来建树。

    (2):建好之后,层次遍历可以采用队列。

 #include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath> using namespace std; vector<int> vect;
vector<int> result; struct Node
{
int value;
Node *left;
Node *right;
}*root; Node *In(int level, int ll, int rr)
{
if (ll > rr) return NULL;
int up_level = pow(, (level - )) - ; //除最后一层外 总共有多少个
int Last_level_left = (rr - ll) + - up_level; //最后一层剩下的 int k = pow(, (level - ) - ); //最后一层是否布满了左分支 int left_left;
if (Last_level_left >= k) left_left = up_level;
else left_left = pow(, (level - )) - + Last_level_left; Node *p = new Node();
p->value = vect[left_left + ll]; p->left = In(level - , ll, ll + left_left - );
p->right = In(level - , ll + left_left + , rr); return p;
} void level_order(Node *root)
{
queue<Node *> q;
q.push(root); while (!q.empty())
{
Node *p = q.front();
q.pop(); result.push_back(p->value); if (p->left != NULL)
q.push(p->left);
if (p->right != NULL)
q.push(p->right);
} printf("%d", result[]);
for (int i = ; i < result.size(); i++)
printf(" %d", result[i]);
printf("\n");
} int main()
{
int n; while (cin >> n)
{
vect.clear();
result.clear();
for (int i = ; i < n; i++)
{
int k;
cin >> k;
vect.push_back(k);
}
sort(vect.begin(), vect.end()); int level = log2(n) + ; root = In(level, , n - );
level_order(root); }
return ;
}
上一篇:Application->ProcessMessages();


下一篇:Android为TV端助力 listview与recyclerview上下联动