例题6-7 树的层次遍历(Trees on the level, Duke 1993, UVa 122)

原题链接:https://vjudge.net/problem/UVA-122
分类:树
备注:二叉树的动态创建与BFS

通过该题复习了一下指针。其实能避免用指针还是尽量避免,本来做题很少用指针,不熟地使用指针就是很容易出错。
注意点:每次出现新结点必须要申请新空间,new申请空间可以用构造函数,读入时得一次性读完,不然操作可能出现问题。

代码如下:

#include<cstdio>
#include<vector>
#include<string>
#include<iostream>
#include<queue>
using namespace std;
const int maxn = 1000 + 5;
vector<int>ans;
bool failed;
struct node {
	int value;
	bool hav_value;
	node* Left, * Right;
};
node* root = new node;
void built(int value, string sub) {
	node *tmp = root;
	for (int i = 0; i < sub.length() - 1; i++) {
		if (sub[i] == 'L') {
			if (tmp->Left == NULL) {
				tmp->Left = new node;
				tmp->Left->hav_value = false;
				tmp->Left->Left = tmp->Left->Right = NULL;
			}
			tmp = tmp->Left;
		}
		else if (sub[i] == 'R') {
			if (tmp->Right == NULL) {
				tmp->Right = new node;
				tmp->Right->hav_value = false;
				tmp->Right->Left = tmp->Right->Right = NULL;
			}
			tmp = tmp->Right;
		}
	}
	if (tmp->hav_value)failed = true;
	tmp->hav_value = true;
	tmp->value = value;
}
bool read() {
	failed = false;
	root->Left = root->Right = NULL;
	root->hav_value = false;
	ans.clear();
	string s;
	while (1) {
		if (!(cin >> s))return false;
		if (s == "()")break;
		int pos = s.find(',', 0);
		int value = 0;
		for (int i = 1; i < pos; i++)
			value = (value << 1) + (value << 3) + s[i] - '0';
		built(value, s.substr(pos + 1));
	}
	return true;
}
bool bfs() {
	node *head = root;
	queue<node*>q;
	q.push(head);
	while (!q.empty()) {
		head = q.front(); q.pop();
		if (!head->hav_value)return false;
		ans.push_back(head->value);
		if (head->Left != NULL)q.push(head->Left);
		if (head->Right != NULL)q.push(head->Right);
	}
	return true;
}
int main(void) {
	while (read()) {
		if (failed || !bfs()) {
			printf("not complete\n");
			continue;
		}
		else {
			for (int i = 0; i < ans.size(); i++)
				printf("%d%c", ans[i], i == ans.size() - 1 ? '\n' : ' ');
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JILIN.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值