PAT-1119(Pre- and Post-order Traversals)+前序和后序遍历确定二叉树+判断二叉树是否唯一

Pre- and Post-order Traversals

PAT-1119

  • 这题难度较大,主要需要考虑如何实现根据前序遍历和后序遍历来确定一颗二叉树
  • 一篇好的文章: 题解
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;
    }
}

posted @   Garrett_Wale  阅读(141)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
历史上的今天:
2019-09-05 POJ-2253(最短路变形+dijikstra算法+求解所有路径中所有最长边中的一个最小值)
2019-09-05 POJ-1062(原始dijiksra算法+思维)
2019-09-05 HDOJ-3416(最大流+最短路+ISAP算法+向前星dijikstra算法+如何判断一条边是否在最短路中)
2019-09-05 HDOJ-4725(Dijikstra算法+拆点求最短路)
点击右上角即可分享
微信分享提示