PAT-1151(LCA in a Binary Tree)+最近公共祖先+二叉树的中序遍历和前序遍历

LCA in a Binary Tree

PAT-1151

  • 本题的困难在于如何在中序遍历和前序遍历已知的情况下找出两个结点的最近公共祖先。
  • 可以利用据中序遍历和前序遍历构建树的思路,判断两个结点在根节点的左右子树,依次递归找到最近祖先
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

/**
 * @Author WaleGarrett
 * @Date 2020/9/5 16:56
 */
public class PAT_1151 {
    static int[] preorder;
    static int[] inorder;
    static Map<Integer,Integer> map;//记录中序遍历数据的序号
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int m=scanner.nextInt();
        int n=scanner.nextInt();
        preorder=new int[n];
        inorder=new int[n];
        map=new HashMap<>();
        for(int i=0;i<n;i++){
            inorder[i]=scanner.nextInt();
            map.put(inorder[i],i);
        }
        for(int i=0;i<n;i++){
            preorder[i]=scanner.nextInt();
        }
        while(m!=0){
            int u=scanner.nextInt(),v=scanner.nextInt();
            //u和v表示待查找的两个结点
            if(map.get(u)==null&&map.get(v)==null){
                System.out.printf("ERROR: %d and %d are not found.\n",u,v);
            }else if(map.get(u)==null||map.get(v)==null){
                System.out.printf("ERROR: %d is not found.\n",map.get(u)==null?u:v);
            } else LCA(0,n-1,0,u,v);
            m--;
        }
    }
    public static void LCA(int inl,int inr,int preroot,int a,int b){
        if(inl>inr)
            return;
        int inroot=map.get(preorder[preroot]);//拿到将中序遍历序列一分为二的值
        int pa=map.get(a),pb=map.get(b);
        if(pa<inroot&&pb<inroot){
            LCA(inl,inroot-1,preroot+1,a,b);
        }else if(pa>inroot&&pb>inroot){
            LCA(inroot+1,inr,preroot+inroot-inl+1,a,b);
        }else if((pa<inroot&&pb>inroot)||(pa>inroot&&pb<inroot)){
            System.out.printf("LCA of %d and %d is %d.\n",a,b,inorder[inroot]);
        }else if(pa==inroot){
            System.out.printf("%d is an ancestor of %d.\n",a,b);
        }else if(pb==inroot){
            System.out.printf("%d is an ancestor of %d.\n",b,a);
        }
    }
}

posted @ 2020-09-05 18:03  Garrett_Wale  阅读(146)  评论(0编辑  收藏  举报