首页 > 编程知识 正文

二叉树的三种遍历例题,中序遍历二叉树的非递归算法

时间:2023-05-06 07:02:44 阅读:29992 作者:454

一、问题说明最近,WYF打算参观他的点卡工厂。 WYF集团经理青色垃圾需要帮助WYF设计“观”路线。 现在青色垃圾知道一些事情:

)1) WYF的点卡工厂构成二叉树。

)2)有n个工厂。

)3) .他为了绘制地图,需要列出以后依次遍历这棵树上的点的方法。

幸运的是,最近他的qcdlq给了他先序扫描和中序扫描的数据。 但是,青色垃圾最近必须帮助解决愈潭宇的问题,没有时间。 请帮助他,为他完成这个任务。 由于青色垃圾的一些特殊要求,WYF的参观路线将是这棵树的推后。

二、问题分析解题思路:以序列开头字母为根节点。 在中序遍历中,根节点处于中序遍历序列的中间,左侧的部分是根节点的左端树的中序遍历序列,右侧的部分是根节点的右端树的中序遍历序列。

三、算法实现节点类:

公共类节点{公共int数据; 公共节点左; 公共节点权限; 公共节点{ }公共节点{ int data } { this.data=data; this.left=null; this.left=null; } }树类:

公共类{私有节点}; //生成器public Tree () { root=null; (/) () ) /后续遍历(@paramlocalroot )/publicvoidsendorder (nodelocalroot ) ) if ) localroot!=空(发送顺序) localroot.left; 发送订单(local root.right; 系统. out.print (local root.data ' ); } } public void sendOrder () this.send order (this.root ); } publicvoidstarttree (int (boforeorder,int ) inOrder ) this.root=this.starttree ) boforeorder,0,boforeorder } por int bEnd,int[] inOrder,int inStart,int inEnd ) if ) bstartbend )。 } int root=beforeOrder[bStart]; 节点头=new node (root; //根节点所在的位置introotindex=searchindex (in order,root,inStart,inEnd ); //左边子树的数量int sum=rootIndex- inStart -1; //构建左子木head.left=start tree (before order,bStart 1,bStart 1 sum,inOrder,inStart,inStart sum ); //右部分树head.right=start tree (before order,bStart 2 sum,bEnd,inOrder,rootIndex 1,inEnd ); 返回头; } publicintsearchindex (int [ ] in order,int root,int statrt,int end ) ) for(intI=statrt; i=end; I ) if(inorder[I]==root ) {返回I; } }返回- 1; } }主类:

import java.util.Scanner; 公共类主{ publicstaticvoidmain (字符串[ ] args ) { Tree tree=new Tree ); sanner scanner=new scanner (system.in; System.out.println ('请输入工厂数量:'); int n=scanner.nextInt (; int[] beforeTree=new int[n]; int[] inTree=new int[n]; System.out.println ('先行遍历:'); for(intI=0; in; I ) { beforeTree[i]=scanner.nextInt (; } System.out.println ()中顺序扫描) ); for(intI=0; in; I({intree[I]=Scanner.nextint ); }tree.starttree(beforetree,inTree ); System.out.println ((二叉树后的遍历) ); tree.sendOrder (; }} 测试

1、测试案例: n=8

依次扫描: 1 2 4 5 7 3 6 8

中序扫描: 4 2 7 5 1 8 6 3

测试结果:

后遍历: 4 7 5 2 8 6 3 1

2、测试案例: n=6

依次扫描: 4 2 6 3 1 5

中序扫描: 6 2 3 4 1 5

测试结果:

后遍历: 6 3 2 5 1 4

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