#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()