您的位置:首页 > 编程语言 > Java开发

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

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();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: