浙大PAT 1102
来源:互联网 发布:java语言无限循环代码 编辑:程序博客网 时间:2024/05/16 04:59
//关键在于找到根节点
#include<iostream>
#include<fstream>#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<math.h>
#include<string>
#include <iomanip>
using namespace std;
int N;
int t=0;
struct node
{
int value;
int left,right;
};
struct treenode
{
int value;
treenode*left,*right;
treenode(){left=right=NULL;value=0;}
};
node *data;
vector<int> tree;
void findroot(int index)
{
if(index==N)
return;
else
{
tree.push_back(data[index].value);
//tree.push_back(data[index].value);
if(data[index].left!=-1)
{
findroot(data[index].left);
}
if(data[index].right!=-1)
{
findroot(data[index].right);
}
}
}
treenode *maketree(int index)
{
if(index==N)
return NULL;
else
{
treenode *temp=new treenode;
temp->value=data[index].value;
if(data[index].left!=-1)
{
temp->left=maketree(data[index].left);
}
if(data[index].right!=-1)
{
temp->right=maketree(data[index].right);
}
return temp;
}
}
void printtreeinorder(treenode *p)
{
if(p)
{
printtreeinorder(p->left);
if(t==0)
cout<<p->value;
else
cout<<" "<<p->value;
t=1;
printtreeinorder(p->right);
}
}
void printtreeleorder(queue<treenode*>p)
{
if(p.size())
{
treenode* top=p.front();
if(t==0)
cout<<top->value;
else
cout<<" "<<top->value;
t=1;
p.pop();
if(top->left)
{
p.push(top->left);
}
if(top->right)
{
p.push(top->right);
}
printtreeleorder(p);
}
}
//#define fin cin
int main()
{
/*ifstream fin("d:\in.txt" );
if (! fin.is_open())
{
cout << "Error opening file";
system("pause");
exit (1);
}*/
cin>>N;
char a,b;
data=new node[N];
for(int i=0;i<N;i++)
{
cin>>a>>b;
data[i].value=i;
if(a=='-')
data[i].right=-1;
else
data[i].right=a-48;
if(b=='-')
data[i].left=-1;
else
data[i].left=b-48;
}
int root=0;
for(int i=0;i<N;i++)
{
tree.clear();
findroot(i);
if(tree.size()==N)
{
root=i;
break;
}
}//data[6] data[7] data[5]
treenode *mytree=maketree(root);
queue<treenode*>p;
p.push(mytree);
printtreeleorder(p);
t=0;
cout<<endl;
printtreeinorder(mytree);
system("PAUSE");
return 0;
}
0 0
- 浙大PAT 1102
- 浙大PAT甲级 1102
- 浙大pat 1017
- 浙大pat Advance 1003
- 浙大PAT目录
- 浙大PAT 1049
- 浙大PAT 1051
- 浙大PAT 1058
- 浙大PAT 1063
- 浙大PAT 1099
- 浙大PAT 1033
- 浙大pat甲级 1023
- 浙大pat甲级 1024
- 浙大pat甲级 1025
- 浙大PAT甲级 1026
- 浙大PAT甲级 1028
- 浙大PAT甲级 1029
- 浙大PAT甲级 1030
- Android性能优化典范之Render Performance
- MySQL最常用命令
- Linux中的initrd
- OC中的Dealloc方法详解
- 欢迎使用CSDN-markdown编辑器
- 浙大PAT 1102
- js颜色选择器
- jquery基础学习之事件
- 欢迎来到测试部-技术交流
- jquery设置元素的readonly和disabled
- Spring事务传播特性
- 常用YUV转RGB代码
- Android应用启动前 白屏或者黑屏原因?
- 理解XML DOM树结构