刘汝佳算法入门经典第二版 二叉树的层次遍历

//二叉树的层次遍历
#include<vector>
#include<iostream>
#include<queue>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn = 300;
char s[maxn];//保存读入的值
bool failed;//标志变量
struct Node
{
    bool have_value;//是否被赋值过
    int v;//结点值
    Node *Left;
    Node *Right;
    Node():have_value(false),Left(NULL),Right(NULL){}//构造函数
};
Node *root;//根结点
Node *newnode(){return new Node();}//申请空间并执行构造函数
void addnode(int v,char *s)
{
    int n = strlen(s);
    Node *u = root;
    for (int i = 0;i<n;i++)
    {
        if(s[i]=='L')
        {
            if(u->Left==NULL)//若节点不存在 建立新节点
                u->Left=newnode();
            u = u->Left; //往左走
        }
        else if(s[i]=='R')
        {
            if(u->Right==NULL)
                u->Right=newnode();
            u = u->Right;
        }
    }//忽略最后的括号
        if(u->have_value)//已经被赋过值
        {
            failed = true;
            //cout<<"*"<<endl;
        }

        u->v = v;
          u->have_value = true;//做标记
}
bool read_inpute()
{
    failed = false;
    root = newnode();//建立根节点
    for(;;)
    {
        if(scanf("%s",s)!=1) return false;
        if(strcmp(s,"()")==0) break;
        int v;
        sscanf(&s[1],"%d",&v);
        addnode(v,strchr(s,',')+1);//strchr函数返回s中从左往右第一个字符“,”的指针
    }
    return true;
}


bool bfs(vector<int> &ans)
{
    queue<Node*> q;
    ans.clear();
    q.push(root);
    while(!q.empty())
    {
        Node *u = q.front();
        q.pop();
        if(!u->have_value)//路径上有的节点只分配了内存空间而没有赋值
            failed = true;
        ans.push_back(u->v);
        if(u->Left!=NULL) q.push(u->Left);
        if(u->Right!=NULL) q.push(u->Right);
    }
    return true;
}

int main()
{
    vector<int>ans;
    vector<int>::iterator it;
    while(read_inpute())
    {
        if(failed == true||root->have_value==false)
        {
            cout<<"not complete"<<endl;
            continue;
        }
        bfs(ans);
        for(it=ans.begin();it!=ans.end();it++)
        {
            if(it==ans.begin())
                cout<<*it;
             else
             cout<<" "<<*it;
        }
        cout<<endl;
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值