题目:
完全二叉树的层序遍历
一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是完美二叉树。对于深度为 D 的,有 N 个结点的二叉树,若其结点对应于相同深度完美二叉树的层序遍历的前 N 个结点,这样的树就是完全二叉树。
给定一棵完全二叉树的后序遍历,请你给出这棵树的层序遍历结果。
输入格式:
输入在第一行中给出正整数 N(≤30),即树中结点个数。第二行给出后序遍历序列,为 N 个不超过 100 的正整数。同一行中所有数字都以空格分隔。
输出格式:
在一行中输出该树的层序遍历序列。所有数字都以 1 个空格分隔,行首尾不得有多余空格。
输入样例:
8
91 71 2 34 10 15 55 18
输出样例:
18 34 55 71 2 10 15 91
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
栈限制
8192 KB
解析:
1
/ \
/ \
/ \
/ \
/ \
2 3
/ \ / \
4 5 6 7
/ \ / \ / \ / \
8 9 10 11 12 13 14 15
每次偏移量的offset数组为:[0 1 0 2 0 1 0 3 0 1 0 2 0 1 0]
第一步:除去非完美二叉树部分。观察可知,四层完全二叉树的叶节点在后序遍历序列的出现位置的每次偏移量组成的序列(简称偏移序列)为[0 1 0 2 0 1 0 3 0 1 0 2 0 1 0],三层完全二叉树的叶节点的偏移序列为[0 1 0 2 0 1 0],两层完全二叉树的叶节点的偏移序列为[0 1 0]...通过观察该规律,可以发现该偏移序列可以通过一个双向队列来递归构造。所以,可以通过该偏移序列将后序遍历序列中的非完全二叉树部分删掉。
第二步:构建完美二叉树部分。使用二分法,先将后序遍历序列的末端出栈,再将剩下的序列二分,以此递归。
第三步:以层序遍历的顺序输出完美二叉树部分与非完美二叉树部分。
代码:
#include<vector>
#include<iostream>
#include<deque>
#include"math.h"
//构建完美二叉树部分
void recursiveRead(std::vector<int> &&p_list, const int &p_depth, int level, std::deque<std::deque<int> > &p_tree) {
if (p_list.empty()) {
return;
}
if (level == p_depth) {
return;
}
p_tree[level].push_back(p_list.back());
p_list.pop_back();
recursiveRead(std::vector(p_list.begin(), p_list.end() - static_cast<int>(p_list.size()) / 2), p_depth, level + 1,
p_tree);
recursiveRead(std::vector(p_list.begin() + static_cast<int>(p_list.size()) / 2, p_list.end()), p_depth, level + 1,
p_tree);
}
//构造偏移序列
std::deque<int> offsetDeque(int depth) {
std::deque<int> offset;
if (depth == -1) {
return offset;
}
offset.push_back(depth);
using Iterator = std::deque<int>::iterator;
std::deque<int> temp = offsetDeque(depth - 1);
for (Iterator i = temp.begin(); i != temp.end(); ++i) {
offset.push_back(*i);
offset.push_front(*i);
}
return offset;
}
int main() {
int N;
std::cin >> N;
std::vector<int> list;
std::vector<int> remainList;
list.reserve(N);
for (int i = 0; i < N; i++) {
int num;
std::cin >> num;
list.push_back(num);
}
const int depth = static_cast<int>(log2(N + 1));
const int remain = N + 1 - static_cast<int>(pow(2, depth));
std::deque<int> offset = offsetDeque(depth);
std::deque<std::deque<int> > tree;
for (int i = 0; i < depth; i++) {
tree.emplace_back();
}
//删除非完美二叉树部分
{
using Iterator = std::deque<int>::iterator;
int j = 0;
int i = 0;
Iterator count = offset.begin();
bool flag = false;
while (j < remain) {
remainList.push_back(list[i]);
list.erase(list.begin() + i);
j++;
i += *count;
++count;
}
}
recursiveRead(std::move(list), depth, 0, tree);
using Iterator = std::deque<std::deque<int> >::iterator;
for (Iterator i = tree.begin(); i != tree.end(); ++i) {
using Iterator = std::deque<int>::iterator;
for (Iterator j = i->begin(); j != i->end(); ++j) {
std::cout << *j;
if (remain == 0 ? (i != tree.end() - 1 || j != i->end() - 1) : true) {
std::cout << " ";
}
}
}
for (int i = 0; i < remain; i++) {
std::cout << remainList[i];
if (i < remain - 1) {
std::cout << " ";
}
}
return 0;
}
结果: