广义表建树+层次遍历

【问题描述】 考研真题:给定一颗二叉树,要求从下至上按层遍历二叉树,每层的访问顺序是从左到右,每一层单独输出一行。

【输入形式】 广义表表示的二叉树,结点元素类型为整型,且都大于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;
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值