二叉树的建立与遍历(binary-tree)
题目描述
给出一棵二叉树,分别输出先序、中序、后序遍历结果。
输入
第一行:结点数n(1<=n<=100)。
以下n行,每行3个整数,分别表示父结点、左孩子、右孩子。若没有孩子,对应的整数为0.
输出
第1行:树根
第2行:先序遍历结果,数字间用1个空格分开。
第3行:中序遍历结果,数字间用1个空格分开。
第4行:后序遍历结果,数字间用1个空格分开。
样例输入
8
1 2 4
2 0 0
4 8 0
3 1 5
5 6 0
6 0 7
8 0 0
7 0 0
样例输出
3
3 1 2 4 8 5 6 7
2 1 8 4 3 6 7 5
2 8 4 1 7 6 5 3
分析:
我们今天学了二叉树,我深有感触。
neixinos();
二叉树是一种很有用(但不好用)的数据结构,在各种题目中都有它的身影。(That's why I hate it)。
二叉树最基本的应用就是遍历,比较常规的遍历方法有:
1.先序:又叫前序,先根,英文为preorder,也叫DLR。具体步骤有:
①访问根结点 ②访问左结点 ③访问右结点
2.中序:又叫中根,英文为inorder,也叫LDR。具体步骤有:
①访问左结点 ②访问根结点 ③访问右结点
3.后序:又叫后根,英文为postorder,也叫LRD。具体步骤有:
①访问左结点 ②访问右结点 ③访问根结点
详见代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<cstdlib>
using namespace std;
struct Epic
{
int data;
int left,right,up;
}tree[123];
int root,n,sp;
void input()
{
int a,b,c;
scanf("%d",&n);
for(int i=1;i<=n;i++) tree[i].data=i;
for(int i=1;i<=n;i++)
{
scanf("%d %d %d",&a,&b,&c);
tree[a].left=b; tree[a].right=c;
tree[b].up=a; tree[c].up=a;
}
for(int i=1;i<=n;i++)
if(!tree[i].up) root=i;
printf("%d\n",root);
}
void DLR(int i)
{
if(i!=0)
{
if(sp) printf(" ");
else sp++;
printf("%d",tree[i].data);
DLR(tree[i].left);
DLR(tree[i].right);
}
}
void LDR(int i)
{
if(i!=0)
{
LDR(tree[i].left);
if(sp) printf(" ");
else sp++;
printf("%d",tree[i].data);
LDR(tree[i].right);
}
}
void LRD(int i)
{
if(i!=0)
{
LRD(tree[i].left);
LRD(tree[i].right);
if(sp) printf(" ");
else sp++;
printf("%d",tree[i].data);
}
}
int main()
{
input();
sp=0; DLR(root);
sp=0; printf("\n"); LDR(root);
sp=0; printf("\n"); LRD(root);
return 0;
}
内心os()
{
好难啊!!!
}