标签:for scan return 如何 sys OLE flag comm ++
import java.util.Scanner;
/**
* @Author WaleGarrett
* @Date 2020/9/5 18:04
*/
public class PAT_1119 {
static int[] preorder;
static int[] postorder;
static boolean flag=true;//判断二叉树是否唯一
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
preorder=new int[n];
postorder=new int[n];
for(int i=0;i<n;i++){
preorder[i]=scanner.nextInt();
}
for(int i=0;i<n;i++){
postorder[i]=scanner.nextInt();
}
PPNode root=buildTree(0,n-1,0,n-1);
if(flag){
System.out.println("Yes");
}else System.out.println("No");
System.out.println(inOrder(root,"").trim());
}
public static PPNode buildTree(int prel,int prer,int postl,int postr){
PPNode root=new PPNode();
root.value=preorder[prel];
if(prel>=prer)
return root;
// System.out.println(prel+" "+prer);
int position=0;
if(prel<prer&&preorder[prel+1]==postorder[postr-1]){
flag=false;//不唯一
//默认为左子树
root.left=buildTree(prel+1,prer,postl,postr-1);
}else{
for(int i=postl;i<postr;i++){
// System.out.println(i+" "+(prel+1));
if(postorder[i]==preorder[prel+1]){
position=i;
break;
}
}
int numl=position-postl+1;
root.left=buildTree(prel+1,prel+numl,postl,position);
root.right=buildTree(prel+numl+1,prer,position+1,postr-1);
}
return root;
}
public static String inOrder(PPNode root,String result){
if(root.left!=null)
result=inOrder(root.left,result);
result=result+root.value+" ";
if(root.right!=null){
result=inOrder(root.right,result);
}
return result;
}
}
class PPNode{
PPNode left;
PPNode right;
int value;
public PPNode(){
left=right=null;
value=-1;
}
}
PAT-1119(Pre- and Post-order Traversals)+前序和后序遍历确定二叉树+判断二叉树是否唯一
标签:for scan return 如何 sys OLE flag comm ++
原文地址:https://www.cnblogs.com/GarrettWale/p/13619434.html