【问题描述】 考研真题:给定一颗二叉树,要求从下至上按层遍历二叉树,每层的访问顺序是从左到右,每一层单独输出一行。
【输入形式】 广义表表示的二叉树,结点元素类型为整型,且都大于0,例如:1( 2( 3 ( 4, 5 ) ), 6( 7, 8( 9, 10 ) ) )
【输出形式】 从下至上,打印每一层的结点元素值,元素间以空格隔开。每层的访问顺序是从左到右,每一层单独输出一行。
【样例输入】 1(2(3(4,5)),6(7,8(9,10))),字符串内没有空格
【样例输出】
4 5 9 10
3 7 8
2 6
1
#include<iostream>
#include<stack>
#include<queue>
#include<vector>
#include<algorithm>
#define maxsize 100
using namespace std;
typedef struct BiNode
{
int date;
BiNode* LChild;
BiNode* RChild;
}*BiTree;
struct Node
{
int date;
int depth;
};
bool cmp(Node n1, Node n2)
{
return n1.depth > n2.depth;
}
void CreateBiTree(BiTree &root, char str[])
{
stack<BiNode*>s; stack<char>num;
int i = 0;
BiNode* cur = NULL;
s.push(root);
while (str[i]!= '\0'&&!s.empty())
{
int falg=-1;//标记
cur = s.top();
char ch = str[i];
if (ch == ')') falg = 0;//')'子树已处理完,直接退栈
else if (ch == '(') falg = 1;//'('处理左子树,左孩子进栈
else if (ch == ',') falg = 2;//','处理右子树,先退栈,然后右孩子进栈
else if(ch>'0'&&ch <= '9')//处理多位数
{
int date = 0; int temp = 1;
num.push(ch);
int j = i+1;
while (str[j] >='0' && str[j] <= '9')
{
num.push(str[j]);
j++;
}
i = j - 1;
while (!num.empty())
{
date += (num.top()-'0')*temp;
temp *= 10;
num.pop();
}
cur->date = date; cur->LChild = NULL; cur->RChild = NULL;
}
switch (falg)
{
case 0: s.pop(); break;
case 1:
cur->LChild = new BiNode;
s.push(cur->LChild); break;
case 2:
s.pop();
cur = s.top();
cur->RChild = new BiNode;
s.push(cur->RChild); break;
default:break;
}
i++;
}
}
vector<Node> bfs(BiTree root)//层次遍历
{
vector<Node>v;
if (root == NULL) return v;
else
{
queue<BiNode*>q;
q.push(root);
BiNode* rear = root;
BiNode* temp = NULL; Node node;
int depth = 1;//深度(层度)
while (!q.empty())
{
temp = q.front();
if (temp->LChild != NULL)
{
q.push(temp->LChild);
}
if (temp->RChild != NULL)
{
q.push(temp->RChild);
}
q.pop();
node.date = temp->date; node.depth = depth;
v.push_back(node);
if (temp == rear)
{
if (!q.empty())
{
rear = q.back();
}
depth++;
}
}
}
return v;
}
void PrintBiTree(vector<Node>v)
{
sort(v.begin(), v.end(), cmp);
for (int i = 0; i < (signed)v.size(); i++)
{
cout << v[i].date << " ";
if (i < (signed)v.size() - 1)
{
if (v[i].depth != v[i + 1].depth)
{
cout << endl;
}
}
else
{
cout << endl;
}
}
}
int main()
{
char str[maxsize];
cin >> str;
BiTree root = new BiNode;
CreateBiTree(root,str);
vector<Node>v;
v=bfs(root);
PrintBiTree(v);
//system("pause");
return 0;
}