这题就是定义了二叉树的结点类型,然后由根节点开始通过解析表达式LR……生成一个树
注意判断一个结点是否被多次赋值,题目要求一个节点多次赋值最后答案要输出错误结论,提交的时候曾经因为这个问题WA了
树的BFS:通过队列实现,一开始先把根节点push,当队列不为空时取出队列头保存,把它的左子结点和右子节点push进队,就可以完成树的层次遍历
代码实现
#include <iostream>
#include <string>
#include <vector>
#include <queue>
using namespace std;
//树的节点
struct node
{
bool have_value;
int value;
node *left;
node *right;
node() {
have_value = false;
left = NULL;
right = NULL;
}
};
node *root; //根节点
bool failed;
//input->addnode->bfs
void addnode(int value, string LR)
{
int n = LR.size();
if (n == 2)
{
root->value = value;
root->have_value = true;
}
else
{
node *temp=root;
for (int i = 1; i < n; i++)
{
if (LR[i] == 'L')
{
if (temp->left == NULL)
temp->left = new node();
temp = temp->left;
}
else if (LR[i] == 'R')
{
if (temp->right == NULL)
temp->right = new node();
temp = temp->right;
}
}
//找到要赋值的节点,准备赋值
if (temp->have_value)
failed = true;
temp->value = value;
temp->have_value = true;
//cout << temp->value << endl;
}
}
bool input()
{
string inputOrder;
failed = false;//判断是否有重复的值
root = new node();
for(;;)
{
if (!(cin >> inputOrder))
return false;
if (inputOrder.size() == 2) //()的情况
break;
int value= stoi(inputOrder.substr(inputOrder.find_first_of("0123456789")));
//cout << value;
string LR = inputOrder.substr(inputOrder.find(","));
//cout << " " << LR << endl;
addnode(value, LR);
}
return true;
}
bool bfs(vector<int> &result) //如果有节点没有被赋值则返回false
{
result.clear();
node *temp = root;
queue<node*> bfsqueue;
if (root->have_value)
bfsqueue.push(temp);
else
return false;
while (!bfsqueue.empty())
{
node *front = bfsqueue.front();
if (front->have_value)
result.push_back(front->value);
else
return false;
bfsqueue.pop();
if (front->left != NULL)
{
bfsqueue.push(front->left);
}
if (front->right != NULL)
{
bfsqueue.push(front->right);
}
}
return true;
}
int main()
{
while (input())
{
vector<int> result;
if (bfs(result)&&(!failed))
{
for (auto it = result.begin(); it != result.end(); it++)
{
if (it == result.begin())
cout << *it;
else
cout << " "<<*it;
}
cout << endl;
}
else
{
cout << "not complete" << endl;
}
}
system("pause");
return 0;
}