题目:
输入二叉树的层次遍历序列,输出其前序遍历序列。
按层次遍历序列为 0 1 2 3 # # 4 # 5 6 #
按先序遍历序列为 0 1 3 # 5 # # # 2 # 4 6 # # #
其中空用“#”代替
输入描述:
第一行输入数字N为层次遍历节点个数
接下来以层次遍历顺序输入N行节点的值(空用“#”代替)
输出描述:
先序遍历结果(空打印为“#”)
考察点:
队列,二叉树
题解:
FIFO,先入先出,队列。
制造树:
- 从根节点开始,一个个节点塞入队列。
- 若该节点(队列首个节点)不是“#”,按从左到右顺序拼接子节点。
- 拼接的子节点入队列。
- 若该节点的左右子节点都接满,从队列中弹出该节点,对后面的节点重复步骤1-3。
输出树:
简单,多加上一个判断——节点值非“#”且无子节点时,打印两行“#”。
本人代码:
#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<cmath>
#include<cctype>
#include<algorithm>
using namespace std;
typedef char ElementType;
class BinaryTree
{
public:
ElementType Val;
BinaryTree* LeftChild;
BinaryTree* RightChild;
BinaryTree(ElementType val = 0)
{
Val = val;
LeftChild = NULL;
RightChild = NULL;
}
BinaryTree* Insert(BinaryTree* BT, ElementType val)
{
BinaryTree* Next = new BinaryTree(val);
if (BT->LeftChild == NULL)
BT->LeftChild = Next;
else if (BT->RightChild == NULL)
BT->RightChild = Next;
return Next;
}
void PreOrder(const BinaryTree* BT) // 递归实现
{
cout << BT->Val << endl;
if (BT->LeftChild)
PreOrder(BT->LeftChild);
if (BT->RightChild)
PreOrder(BT->RightChild);
if (BT->LeftChild == NULL && BT->RightChild == NULL && BT->Val != '#') //无子节点最后也要输出两行##
{
cout << "#" << endl;
cout << "#" << endl;
}
return;
}
};
int main()
{
int N;
while (cin >> N)
{
string str;
for (int i = 0; i < N; i++)
{
char tmp;
cin >> tmp;
str.push_back(tmp);
}
BinaryTree* BT = new BinaryTree(str[0]);
vector<BinaryTree*> Order;
Order.push_back(BT);
for (int i = 1; i < N; i++)
{
while (Order[0]->Val == '#')
{
Order.erase(Order.begin());
}
BinaryTree* Next = Order[0]->Insert(Order[0], str[i]);
Order.push_back(Next);
if (Order[0]->RightChild )
Order.erase(Order.begin());
}
Order.clear();
cout << endl << endl;
BT->PreOrder(BT);
}
system("pause");
return 0;
}
/*
11
0
1
2
3
#
#
4
#
5
6
#
*/
信息来自同实验室应届硕士毕业生。