题目
简单说:
- 输入**(11,LL) (7,LLL) (8,R) (5,) (4,L) (12,RL) (2,LLR) (1,RRR) (4,RR) (),每个括号对应一个节点,()**代表结束,L代表左孩子,R代表右孩子,每个节点之间存在一个空格分割。
- 输出:5 4 8 11 13 4 7 2 1
解答
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
typedef struct Node{
bool have_value;
string v;
Node *left,*right;
Node():have_value(false),left(NULL),right(NULL){}
}Node;
Node *root;
Node* newnode()
{
return new Node();
}
void AddNode(string value,string LR)
{
Node *tem_root = root;
for(int i=0;i<LR.length();++i)
{
if(LR[i]=='R')
{
if(tem_root->right==NULL) tem_root->right = newnode();
tem_root = tem_root->right;
}
if(LR[i]=='L')
{
if(tem_root->left==NULL) tem_root->left = newnode();
tem_root = tem_root->left;
}
}
tem_root->v = value;
tem_root->have_value = true;
}
void Read_string()
{
string str;
root = newnode();
while(1)
{
cin>>str;
if (str.find(')')-str.find('(')==1) break;
int po = str.find(',');
string num = str.substr(1,po-1);
string s = str.substr(po+1,str.length()-2-po);
AddNode(num,s);
}
}
//利用队列来实现广度优先,即将节点一次放入队列,然后从队列头部依次读取下一深度
bool BFS(vector<string>& ans)
{
queue<Node*> q;
ans.clear();
q.push(root);
while(!q.empty())
{
Node *u = q.front();
q.pop();//去除最前面的
if(!u->have_value) return false;
ans.push_back(u->v);
if(u->left!=NULL) q.push(u->left);
if(u->right!=NULL) q.push(u->right);
}
return true;
}
void remove_tree(Node *u)
{
if(u == NULL) return;
remove_tree(u->left);
remove_tree(u->right);
delete u;
}
int main()
{
Read_string();
vector<string> ans;
BFS(ans);
for(int i=0;i<ans.size();++i)
cout<<ans[i]<<" ";
remove_tree(root);
}
总结
简单来说,广度优先就是先用queue来依次存放节点,队首先pop出一个节点,然后访问其左右子节点,并且非空放入队列,然后将该节点的值放入新的容器,如vector。直至queue为空。以上一些基本概念,在本人的博客中,都有过解释,不太明白的朋友,可以去了解一下。