标签:silver 等级 输入 pad using 节点 struct one text
求一棵二叉树的前序遍历,中序遍历和后序遍历
第一行一个整数n,表示这棵树的节点个数。
接下来n行每行2个整数L和R。第i行的两个整数Li和Ri代表编号为i的节点的左儿子编号和右儿子编号。
输出一共三行,分别为前序遍历,中序遍历和后序遍历。编号之间用空格隔开。
5
2 3
4 5
0 0
0 0
0 0
1 2 4 5 3
4 2 5 1 3
4 5 2 3 1
n <= 16
1 #include<iostream> 2 using namespace std; 3 #include<cstdio> 4 struct tree{ 5 int l; 6 int r; 7 }; 8 tree s[10010]; 9 void qian(int x) 10 { 11 cout<<x<<" "; 12 if(s[x].l)qian(s[x].l); 13 if(s[x].r)qian(s[x].r); 14 } 15 void zhong(int x) 16 { 17 if(s[x].l)zhong(s[x].l); 18 cout<<x<<" "; 19 if(s[x].r)zhong(s[x].r); 20 } 21 void hou(int x) 22 { 23 if(s[x].l)hou(s[x].l); 24 if(s[x].r)hou(s[x].r); 25 cout<<x<<" "; 26 } 27 int main() 28 { 29 int n; 30 cin>>n; 31 for(int i=1;i<=n;++i) 32 scanf("%d%d",&s[i].l,&s[i].r); 33 qian(1);cout<<endl; 34 zhong(1);cout<<endl; 35 hou(1); 36 return 0; 37 }
1 #include<iostream> 2 using namespace std; 3 #include<cstdio> 4 struct tree{ 5 int l; 6 int r; 7 }; 8 tree s[10010]; 9 void qian(int x) 10 { 11 cout<<x<<" "; 12 if(s[x].l)qian(s[x].l); 13 if(s[x].r)qian(s[x].r); 14 } 15 void zhong(int x) 16 { 17 if(s[x].l)zhong(s[x].l); 18 cout<<x<<" "; 19 if(s[x].r)zhong(s[x].r); 20 } 21 void hou(int x) 22 { 23 if(s[x].l)hou(s[x].l); 24 if(s[x].r)hou(s[x].r); 25 cout<<x<<" "; 26 } 27 int main() 28 { 29 int n; 30 cin>>n; 31 for(int i=1;i<=n;++i) 32 scanf("%d%d",&s[i].l,&s[i].r); 33 qian(1);cout<<endl; 34 zhong(1);cout<<endl; 35 hou(1); 36 return 0; 37 }
标签:silver 等级 输入 pad using 节点 struct one text
原文地址:http://www.cnblogs.com/mjtcn/p/6666159.html