HDU-1622

#include <bits/stdc++.h>
using namespace std;
struct node {
	int value;
	int flag;//判断当前结点有没有被赋值或者多次遍历 数值代表赋值几次
	node* l, * r;
	node(int value = 0, node* l = NULL, node* r = NULL) :value(value), l(l), r(r) { flag = 0; }
};
node* root = NULL;
void Bfs() {
	queue<node> q;
	q.push(*root);
	while (!q.empty()) {
		node n = q.front();
		q.pop();
		cout << n.value << " ";
		if (n.l != NULL)
			q.push(*n.l);
		if (n.r != NULL)
			q.push(*n.r);
	}
	cout << endl;
}
void insert(node*& root, string s, int now, int value) {
	if (now == s.size()) {
		if (root == NULL) {
			root = new node(value);
			root->flag = 1;
		}
		else {
			root->value = value;
			root->flag++;
		}
	}
	else {
		//先创建root
		if (root == NULL)
			root = new node();
		if (s[now] == 'L')
			insert(root->l, s, now + 1, value);
		if (s[now] == 'R')
			insert(root->r, s, now + 1, value);
	}
}
bool checked() {
	if (!root) return true;
	queue<node> q;
	q.push(*root);
	while (!q.empty()) {
		node n = q.front();
		q.pop();
		if (n.flag != 1) return false;
		if (n.l != NULL)
			q.push(*n.l);
		if (n.r != NULL)
			q.push(*n.r);
	}
	return true;
}
void ClearTree(node *& root) {
	if (!root) return;
	ClearTree(root->l);
	ClearTree(root->r);
	delete root;
	root = NULL;
}
int main() {
	string s;

	while (cin >> s) {
		if (s == "()") {
			if (root) {
				if (checked()) {
					Bfs();
				}
				else {
					cout << "not complete" << endl;
				}
			}
			ClearTree(root);
		}
		else {
			int value;
			string path;
			s = s.substr(1, s.size() - 2); // 去掉括号
			size_t comma = s.find(',');
			value = stoi(s.substr(0, comma));
			path = s.substr(comma + 1);
			insert(root, path,0, value);
		}
	}
	return 0;
}

这是正经自己独立写出来的第一个树代码:

两个注意的点:

1.insert插入的时候 如果结点为空要先new再递归

2.flag代表记录次数

3.对字符串api熟悉使用

string.substr() string.find() 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值