算法题训练--广度优先实现树的遍历 (c++中,vector,queue,struct的使用)

题目

简单说:

  • 输入**(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为空。以上一些基本概念,在本人的博客中,都有过解释,不太明白的朋友,可以去了解一下。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Hanzoe_lwh

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

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

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

打赏作者

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

抵扣说明:

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

余额充值