java实现——L2-006. 树的遍历
2017-03-23 13:48
309 查看
因为本人数据结构渣渣,这题想了一天半吧,也参考了网上别人做的,因为很多都是C++做的,所以我这里提供一份java的代码,给有需要的人学习,有解释,如果看不懂的就自己领悟吧!
时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class 树的遍历2 { class Tree { public Tree left; public Tree right; public int root; public Tree(int root) { this.root = root; this.left = null; this.right = null; } } int[] postorder = null;//后序数组 int[] inorder = null;//中序数组 int n = 0; public void init() { Scanner sc = new Scanner(System.in); n = sc.nextInt(); postorder = new int ; inorder = new int ; for (int i = 0; i < n; i++) { postorder[i] = sc.nextInt(); } for (int j = 0; j < n; j++) { inorder[j] = sc.nextInt(); } Tree root = buildT(0, n, 0, n); bfs(root); } // al,ar表示后序遍历的区间[al,ar],bl,br表示中序遍历的区间[bl,br] public Tree buildT(int pl, int pr, int il, int ir) { int i = 0; if(pl >= pr||il == ir){ return null; } Tree root = null; for (i = il; i < ir; i++) { if (postorder[pr-1] == inorder[i]) {//取出根结点下标,以根结点做为分隔结点 break; } } root = new Tree(postorder[pr-1]);//后序数组中的最后一个肯定是根结点,因为我开的数组是从0开始的,所以要减一,要不等下就会有溢出异常 root.left = buildT(pl, pr-ir+ i, il, i);//这里就是这个pr-ir+i有些难理解,就是后序遍历每次取最后一个做为根结点,那么等下就会出会中 //序与后序的下标不同步,而i为中序的下标,只有当pr-lr之间的差值加上i之后得到就会是后序的下标 root.right = buildT(pl, pr-1, i+1, ir); return root; } //层序遍历,一般都是用队列做,方便,每次在队列只加入一个节点,附加打印其值,再将它的左节点加入,取值,再将右节点加入队列,取值,直到队列为空 public void bfs(Tree root){ if(root==null) return; Queue<Tree> q = new LinkedList<Tree>(); q.offer(root); int count=0; while(!q.isEmpty()){ count++;//这个count只是为了做满足题目的“数字间以1个空格分隔,行首尾不得有多余空格。" Tree temp = q.poll(); if(count==n) System.out.print(temp.root); else System.out.print(temp.root+" "); if(temp.left!=null) q.add(temp.left); if(temp.right!=null) q.add(temp.right); } } public static void main(String[] args) { 树的遍历2 a = new 树的遍历2(); a.init(); } }
相关文章推荐
- Java 多叉树的实现,完成树的初始化和遍历
- L2-006. 树的遍历
- java实现二叉树及遍历
- Java实现通过递归遍历树形结构
- JAVA语言实现二叉树的层次遍历的非递归算法及递归算法
- 二叉树的非递归前序,中序,后序遍历的Java实现
- java实现二叉树的创建及5种遍历
- 二叉树的前序,中序,后序遍历Java实现
- LeetCode OJ平台上Linked List Cycle题目用java快慢遍历实现
- L2-006. 树的遍历(利用后序中序还原二叉树)
- 备考蓝桥杯(26)漏掉的账单明细,(遍历所有情况)(java实现)(exforward)
- java中Set集合的遍历及实现类比较分析
- 邻接表存储图,DFS遍历图的java代码实现
- 二叉树的三种遍历方式java实现
- Java实现图的遍历(深度优先与广度优先遍历)
- Java用Field实现对象的拷贝,遍历对象字段、取值赋值
- L2-006. 树的遍历 -天梯赛练习题
- JAVA实现二叉树的前、中、后序遍历
- Java实现文件的遍历 类型匹配(图形化界面)
- java实现二叉树的构建以及3种遍历方法