本題主要要解決的只有兩個問題
一個是通過前序遍歷和中序遍歷得出原二叉樹
二時對樹層序遍歷
其實與其説是對樹的鏡像遍歷,我們完全可以不用管他的鏡像,只需改一下層序遍歷的順序即可
import java.io.BufferedInputStream;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class HeroNode{
int data;
HeroNode left,right;
}
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n=scan.nextInt();
int[]in=new int[n+1];
int[]pre=new int[n+1];
for(int i=0;i<n;i++){
in[i]=scan.nextInt();
}
for(int i=0;i<n;i++){
pre[i]=scan.nextInt();
}
HeroNode root=BuildTree(in,0,pre,0,n);
LevelOrder(root);
}
public static HeroNode BuildTree(int[]in,int is,int[]pre,int ps,int n){
if(n<=0)
return null;
HeroNode heroNode=new HeroNode();
heroNode.data=pre[ps];
int i;
for(i=0;i<n;i++){
if(in[i+is]== heroNode.data)
break;
}
heroNode.left=BuildTree(in,is,pre,ps+1,i);
heroNode.right=BuildTree(in,i+1+is,pre,ps+i+1,n-1-i);
return heroNode;
}
public static void LevelOrder(HeroNode node){
boolean isFlag=false;
HeroNode current=node;
if(current==null)
return;
Queue<HeroNode>queue=new LinkedList<HeroNode>();
queue.offer(current);
while(!queue.isEmpty()){
current=queue.poll();
if(isFlag==false){
System.out.print(current.data);
isFlag=true;
}else{
System.out.print(" "+current.data);
}
if(current.right!=null){//因爲是對鏡像進行層序,所以只需把存入隊列的順序調換即可
queue.offer(current.right);
}
if(current.left!=null){
queue.offer(current.left);
}
}
}
}
此外,本體還有不用建樹的方法: