题目描述
给定一棵二叉树的前序(根、左、右)和中序(左、根、右)的打印结果,输出此二叉树按层(从左往右)打印结果。
例如一棵二叉树前序:1 2 4 5 3;中序:4 2 5 1 3。可以构建出下图所示二叉树:
按层打印的结果则为:1 2 3 4 5。
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Node{
public int value;
public Node left;
public Node right;
public Node(int value){
this.value=value;
this.left=null;
this.right=null;
}
}
public class BinaryTree
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] preSort = null;
int[] inSort = null;
while(sc.hasNext()){
int number = sc.nextInt();
preSort = new int[number];
for(int i=0; i<number; i++){
preSort[i] = sc.nextInt();
}
inSort = new int[number];
for(int i=0; i<number; i++){
inSort[i] = sc.nextInt();
}
//创建二叉树的先序遍历和中序遍历
/*int[] preSort = {1,2,4,5,3};
int[] inSort = {4,2,5,1,3};*/
Node root = constructCore(preSort, inSort);
levelTravel(root);
}
}
public static Node constructCore(int[] preSort, int[] inSort){
//递归结束条件
if(preSort == null || inSort == null){
return null;
}
/**第一次没有判断长度,导致执行一半时候,数组下标越界,一直没找到原因,之前错误以为判断数组为空和数组长度为零是一样的
*/
if(preSort.length == 0 || inSort.length == 0){
return null;
}
if(preSort.length != inSort.length){
System.out.println("illegal input!");
}
//创建一个根节点
Node root = new Node(preSort[0]);
//System.out.println("priamry value:"+root.value);
for(int i=0; i<inSort.length; i++){
if(preSort[0] == inSort[i]){
//root.value = inSort[i];
//System.out.println(root.value);
//递归遍历
root.left = constructCore(Arrays.copyOfRange(preSort, 1, i+1), Arrays.copyOfRange(inSort, 0, i));
root.right = constructCore(Arrays.copyOfRange(preSort, i+1, preSort.length), Arrays.copyOfRange(inSort, i+1, inSort.length));
}
}
return root;
}
public static void levelTravel(Node root){
if(root==null) return;
Queue<Node> q=new LinkedList<Node>();
q.offer(root);
while(!q.isEmpty()){
Node temp = q.poll();
System.out.print(temp.value+" ");
if(temp.left!=null) q.offer(temp.left);
if(temp.right!=null) q.offer(temp.right);
}
}
}
备注:
在java5中新增加了java.util.Queue接口,用以支持队列的常见操作。Queue接口与List、Set同一级别,都是继承了Collection接口。
Queue使用时要尽量避免Collection的add()和remove()方法,而是要使用offer()来加入元素,使用poll()来获取并移出元素。它们的优
点是通过返回值可以判断成功与否,add()和remove()方法在失败的时候会抛出异常。 如果要使用前端而不移出该元素,使用
element()或者peek()方法。
值得注意的是LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。
去哪网笔试 按层打印二叉树 Java实现
最新推荐文章于 2024-07-31 16:30:56 发布