首页 > 编程知识 正文

数据结构二叉树的遍历,二叉树中序遍历

时间:2023-05-04 00:30:04 阅读:157338 作者:3065

本文的代码是java代码

一、二叉树

二叉树Binary Tree是n(n=0)个节点的有限集合,该集合由空集合(称为空二叉树)、或者一个根节点和两个树互不相交的分别被称为根节点的左右子树的二叉树构成。 -- 《大话数据结构》

简单来说,二叉树是树,最多有两个子树。 图1-1 :

代码显示:

公共类树节点{

公共int val;

公共树左;

public TreeNode right;

公共treenode (intx ) { val=x; }

}

二.二叉树遍历

1、前一个遍历

前面遍历的顺序是根节点左边的子树右边的子树,遍历子树时也可以用同样的顺序用递归的想法来理解。 排线顺序如图2-1 :

代码显示:

publicstaticvoidprevprinttreenode {

if(root==null ) {

返回;

}

system.out.print(root.val ' );

//使用了递归

prevprinttreenode(root.left;

prevprinttreenode(root.right;

}

结果为{ 1,2,3,4,5,6 }。 可以看到,先前遍历结果的第一个节点是根节点。

2、中序扫描

中顺扫描的顺序是左子木-根节点-右子木。 排线顺序如图2-2 :

代码显示,仅顺序不同:

publicstaticvoidinprinttreenode {

if(root==null ) {

返回;

}

//使用了递归

inprinttreenode(root.left;

system.out.print(root.val ' );

inprinttreenode(root.right;

}

结果为{ 3,2,1,5,4,6 }。 可见中顺遍历根节点左侧均为左子树节点,右侧均为右子树节点。

3、后续横移

后面的遍历顺序为左侧子树-右侧子树-根节点,遍历顺序如图2-3所示。

代码表示依然只有顺序的不同:

publicstaticvoidpostprinttreenode {

if(root==null ) {

返回;

}

//使用了递归

postprinttreenode(root.left;

postprinttreenode(root.right;

system.out.print(root.val ' );

}

结果为{ 3,2,5,6,4,1 }。 可知之后追寻最后的节点是根节点。

4、根据遍历结果推导二叉树

二叉树结构通过前相遍历或后相遍历得到根节点,中相遍历在根节点已知的情况下可以获知左子树和右子树的遍历结果,与前相遍历结果、中相遍历结果、已知的后相遍历结果的中相对比但是,由于无法判断左子树和右子树的节点数,所以已知无法导出先行节点和后续节点。 例如,如果二叉树的前相遍历结果为{ 1,2,3 },后相遍历结果为{ 3,2,1 },则有如图2-4所示的4种可能性。

三.根据前相遍历和中相遍历结果恢复二叉树

原理的第2节已经叙述过了,再画一些图以便于理解。 见图3-1 :

得到图1-1的二叉树。

代码实现:

公共类解决方案{

publicstatictreenodereconstructbinarytree (int [ ] prev,int [] in ) {

()无论采用什么样的遍历方法,结果的长度都一定相同,是总结分数

if(prev.length!=in.length || prev.length1) {

返回空值;

}

//只有一个节点,根节点

if(prev.length==1) {

returnnewtreenode(prev[0];

}

//在中顺序遍历结果中查找根节点

int index=-1;

for(intI=0; I

if(in[I]==prev[0] ) {

索引=I;

黑;

}

}

//未找到。 数据有问题

if (索引==-1 ) {

返回空值;

}

//找到根节点

treenode root=new treenode (prev [0];

) )获得左子树前序遍历的结果

int[] lChildPrev=new int[index];

system.arraycopy(prev,1,lChildPrev,0,index );

) )得到左子树的中顺扫描的结果

int[] lChildin=new int[index];

system.arraycopy(in,0,lChildin,0,index );

) )通过递归,得到左子树结构

root.left=reconstructbinarytree (lchild prev,lChildin );

//得到右部分树的前序遍历的结果

int [ ] rchild prev=new int [ in.length-1-index ];

system.arraycopy(prev,index 1,rChildPrev,0,in.length-1-index );

//得到右部分树的中顺遍历结果

int [ ] rchild in=new int [ in.length-1-index ];

system.arraycopy(in,index 1,rChildin,0,in.length-1-index );

//通过递归,得到右部分树结构

root.right=reconstructbinarytree (rchild prev,rChildin );

//得到完整的二叉树结构

返回根;

}

//测试

publicstaticvoidmain (string [ ] args ) {

int [ ] prev={ 1,2,4,7,3,5,6,8 };

int [ ] in={ 4,7,2,1,5,3,8,6 };

treenode root=reconstructbinarytree (prev,in );

prevprinttreenode(root;

System.out.println (;

inprinttreenode(root;

}

//测试结果

//1 2 4 7 3 5 6 8

//4 7 2 1 5 3 8 6

}

正文结束。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。