</pre><pre name="code" class="cpp">
//
// main.cpp
// 层次遍历
//
// Created by 张嘉韬 on 16/2/1.
// Copyright © 2016年 张嘉韬. All rights reserved.
//
#include <cstring>
#include <iostream>
#include <cmath>
using namespace std;
int counter,pcounter,b[1000];
struct Node //创建节点结构
{
bool flag; //判断该节点是否被赋过值
int value;
struct Node *left;
struct Node *right;
};
Node *a[1000];
Node *creat (int deep)//创建二叉树,由于二叉树是递归定义的,所以我们也使用递归结构来创建二叉树
{
Node *p=new Node;
p->flag=0;
if(deep<=8)
{
p->left=creat(deep+1);
p->right=creat(deep+1);
}
else
{
p->left=NULL;
p->right=NULL;
}
return p;
}
void bfs(Node* p)
{
int head,end;
head=0,end=0;
a[head]=p;
//cout<<a[head]->value<<endl;
while(head<=end)
{
pcounter++;
b[pcounter]=a[head]->value;
if(a[head]->left!=NULL)
{
if(a[head]->left->flag==1)
{
end++;
a[end]=a[head]->left;
}
if(a[head]->right->flag==1)
{
end++;
a[end]=a[head]->right;
}
}
head++;
}
}
int main()
{
freopen("/Users/zhangjiatao/Desktop/input.txt","r",stdin);
memset(b,0,sizeof(b));
Node *root;
char s[50];
root=creat(1);
counter=0;
pcounter=0;
while(scanf("%s",s)&&strlen(s)!=2)
{
int sum,len,p;
Node *temp;
temp=root;
len=sum=0;
p=1;
while(s[p]!=',')
{
len++;
p++;
}
for(int i=len;i>=1;i--)//将字符串数字转化为整形数字
{
sum+=(s[len-i+1]-48)*pow(10,i-1);
}
p++;
if(s[p]==')') temp->value=sum;
while(s[p]!=')')//寻找节点
{
if(s[p]=='L') temp=temp->left;
else temp=temp->right;
p++;
}
if(temp->flag==0)
{
temp->value=sum;
temp->flag=1;
counter++;
}
else
{
cout<<"-1"<<endl;
return 0;
}
}
bfs(root);
if(counter!=pcounter) cout<<"-1";
else
{
for(int i=1;i<=counter;i++)
cout<<b[i]<<" ";
}
cout<<endl;
return 0;
}
总结:
每个问题都值得我们从头到位去认真的思考应该怎么去实现,而不是去翻书去百度,我们应该更加依赖自己的思考,经过这道题目的实现,我们解决了很多问题,这个过程大概都是 要先清晰我们要解决的问题,然后设计大概框架,然后写伪代码,再去试实现,这也充分证明了思考再程序设计上的重要性。