二叉树的建立与遍历【图论】【二叉树】

来源:互联网 发布:黄山招聘美工 编辑:程序博客网 时间:2024/05/29 15:50
二叉树的建立与遍历(binary-tree)


题目描述
给出一棵二叉树,分别输出先序、中序、后序遍历结果。


输入
第1行:结点数n(1<=n<=100)


以下若干行,每行3个整数,分别表示父结点、左孩子、右孩子。若没有孩子,对应的整数为0.


输出
第1行:树根


第2行:先序遍历结果,数字间用1个空格分开。


第3行:中序遍历结果,数字间用1个空格分开。


第4行:后序遍历结果,数字间用1个空格分开。


样例输入


样例输出
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



首先,我们要找树根,这很简单,哪个结点没有父节点,那么,他就是树根。用一个for就可完成



然后要进行3个深搜:



(1)

先序:

即先访问根节点,在访问左子节点,最后访问右子节点;

(2)

中序:

即先访问左子节点,在访问根节,最后访问右子节点;


(1)

后序:

即先访问左子节点,在访问右子节点,最后访问根节点


代码如下

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

struct node
{
int father,left,right;//父节点,左子节点,右子节点
};
node tree[110];
int f[110],root;
int l;
void f1(int x)//先序
{
if(f[x]||!x) return ;
f[x]=1;
if(x!=root) printf(" %d",x);
if(tree[x].left) f1(tree[x].left);
if(tree[x].right) f1(tree[x].right);
}


void f2(int x)//中序
{
if(f[x]||!x) return ;
f[x]=1;
if(tree[x].left) f2(tree[x].left);
if(x!=l) printf(" %d",x);
if(tree[x].right) f2(tree[x].right);
if(tree[x].father) f2(tree[x].father);
}


void f3(int x)//后序
{
if(f[x]||!x) return ;
f[x]=1;
if(tree[x].left) f3(tree[x].left);
if(tree[x].right) f3(tree[x].right);
if(x!=l) printf(" %d",x);
if(tree[x].father) f3(tree[x].father);
}


int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
int h,hh,hhh;
scanf("%d%d%d",&h,&hh,&hhh);
tree[h].left=hh; tree[h].right=hhh;
tree[hh].father=h; tree[hhh].father=h;
}
for(int i=1;i<=n;i++)//找树根
if(tree[i].father==0) root=i;
printf("%d\n",root);
l=root;
for(;;)//找最左叶节点
{
if(tree[l].left!=0) l=tree[l].left;
else break;
}
printf("%d",root);f1(root);printf("\n");//从根节点开始找
memset(f,0,sizeof(f));
printf("%d",l);f2(l);printf("\n");//从最左叶节点开始找
memset(f,0,sizeof(f));
printf("%d",l);f3(l);//从最左叶节点开始找
}



2 1
原创粉丝点击