PAT-1102(Invert a Binary Tree)+二叉树的镜像+层次遍历+中序遍历+已知树的结构构树
Invert a Binary Tree
pat-1102
import java.util.Arrays;
import java.util.Queue;
import java.util.Scanner;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @Author WaleGarrett
* @Date 2020/9/5 20:04
*/
public class PAT_1102 {
static InvertTree[] tree;
static boolean[] flag;
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
tree=new InvertTree[n];
flag=new boolean[n];
Arrays.fill(flag,false);
scanner.nextLine();
for(int i=0;i<n;i++){
String a=scanner.next(),b=scanner.next();
int na,nb;
if(a.equals("-")){
na=-1;
}else {
na=Integer.parseInt(a);
flag[na]=true;
}
if(b.equals("-")){
nb=-1;
}else {
nb=Integer.parseInt(b);
flag[nb]=true;
}
tree[i]=new InvertTree();
tree[i].left=na;
tree[i].right=nb;
}
int head=-1;
for(int i=0;i<n;i++){
if(!flag[i]){
head=i;
break;
}
}
System.out.println(levelOrder(head,"").trim());
System.out.println(inOrder(head,"").trim());
}
public static String levelOrder(int head,String result){
Queue<Integer> que=new LinkedBlockingQueue<>();
que.add(head);
while(!que.isEmpty()){
int now=que.poll();
result=result+now+" ";
if(tree[now].right!=-1) que.add(tree[now].right);
if(tree[now].left!=-1) que.add(tree[now].left);
}
return result;
}
public static String inOrder(int head,String result){
if(head==-1)
return result;
result=inOrder(tree[head].right,result);
result=result+head+" ";
result=inOrder(tree[head].left,result);
return result;
}
}
class InvertTree{
int left,right,value;
}
Either Excellent or Rusty