zoukankan      html  css  js  c++  java
  • Leecode no.889 根据前序和后序遍历构造二叉树

    package tree;

    import java.util.Arrays;

    /**
    *
    * 889. 根据前序和后序遍历构造二叉树
    * 返回与给定的前序和后序遍历匹配的任何二叉树。
    *
    * pre 和 post 遍历中的值是不同的正整数。
    *
    * @author Tang
    * @date 2021/7/29
    */
    public class ConstructFromPrePost {

    /**
    * 思路: 对于当前节点 拆分出左子树有哪些节点,右子树有哪些节点
    * 根据 前序遍历的第二个节点是左子节点的性质 找到第二个节点在后续遍历中的位置,从而判断左子树节点个数
    * @param preorder
    * @param postorder
    * @return
    */
    public TreeNode constructFromPrePost(int[] preorder, int[] postorder) {
    if(preorder.length == 0){
    return null;
    }
    TreeNode root = new TreeNode(preorder[0]);
    if(preorder.length == 1){
    return root;
    }
    int leftCount = 0;
    for(int i = 0; i < postorder.length; i++){
    if(postorder[i] == preorder[1]){
    leftCount = i+1;
    }
    }
    //左子树递归
    root.left = constructFromPrePost(Arrays.copyOfRange(preorder, 1, leftCount+1),
    Arrays.copyOfRange(postorder, 0, leftCount));
    //右子树递归
    root.right = constructFromPrePost(Arrays.copyOfRange(preorder, leftCount+1, preorder.length),
    Arrays.copyOfRange(postorder, leftCount, postorder.length - 1));
    return root;
    }


    public static void main(String[] args) {

    }


    }
  • 相关阅读:
    xPath用法
    http post 接口
    关于WSSE验证-- 一种验证用户的方法
    java资源文件解读
    dom4j读取xml
    docker安装mysql
    php.ini配置max_execution_time和FPM配置request_terminate_timeout
    《高德拉特约束理论》
    Python爬虫-播报天气信息(生成exe文件)待续
    pyhon-爬虫实战抓取豆瓣top250到mysql
  • 原文地址:https://www.cnblogs.com/ttaall/p/15076989.html
Copyright © 2011-2022 走看看