二叉树遍历

二叉树遍历:

① NLR:前序遍历(PreorderTraversal亦称(先序遍历))

——访问根结点的操作发生在遍历其左右子树之前。

若二叉树非空,则依次执行如下操作:

⑴ 访问根结点;

⑵ 遍历左子树;

⑶ 遍历右子树。

② LNR:中序遍历(InorderTraversal)

——访问根结点的操作发生在遍历其左右子树之中(间)。

若二叉树非空,则依次执行如下操作:

⑴遍历左子树;

⑵访问根结点;

⑶遍历右子树。

③ LRN:后序遍历(PostorderTraversal)

——访问根结点的操作发生在遍历其左右子树之后。

若二叉树非空,则依次执行如下操作:

⑴遍历左子树;

⑵遍历右子树;

⑶访问根结点。

实现:

前序遍历

procedure first(i:longint);

begin

write(a[i]);

if a[i*2]<>0 then first(i*2);

if a[i*2+1]<>0 then first(i*2+1);

end;

中序遍历

procedure mid(i:longint);

begin

if a[i*2]<>0 then mid(i*2);

write(a[i]);

if a[i*2+1]<>0 then mid(i*2+1);

end;

后序遍历

procedure last(i:longint);

begin

if a[i*2]<>0 then last(i*2);

if a[i*2+1]<>0 then last(i*2+1);

write(a[i]);

end;

 

出题类型:

1、

该图的先序遍历:

ABDCEF

中序遍历:

DBAECF

后序遍历:

DBEFCA

2、给出先序遍历、中序遍历、后序遍历的任意两种,写出另外一种遍历的结果。

3、写出三种遍历算法实现

注意:

中序投影法

计算中序遍历拥有比较简单直观的投影法,如图

 

 

  中序遍历的投影法

 

原文地址:https://www.cnblogs.com/keanuyaoo/p/3325060.html