【算法二十五】105. 从前序与中序遍历序列构造二叉树 236. 二叉树的最近公共祖先

105. 从前序与中序遍历序列构造二叉树

递归:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    Map<Integer,Integer> hashmap;
    //中左右 左中右
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        hashmap = new HashMap<>();
        int n = preorder.length;
        for(int i = 0; i<n;i++){
            hashmap.put(inorder[i],i);
        }
        return buildMyTree(preorder,inorder,0,n-1,0,n-1);
    }
    
    private TreeNode buildMyTree(int[] preorder,int[] inorder,int pl,int pr, int il,int ir){
        if(pl>pr){
            return null;
        }
        int rootVal = preorder[pl];
        TreeNode root = new TreeNode(rootVal);
        int index = hashmap.get(rootVal);
        int leftTreeLen = index - il;
        root.left = buildMyTree(preorder,inorder,pl+1,pl+leftTreeLen,il,index-1);
        root.right = buildMyTree(preorder,inorder,pl+leftTreeLen+1,pr,index+1,ir);
        return root;
    }
}

时间复杂度:O(N)

空间复杂度:O(N)

236. 二叉树的最近公共祖先

递归:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q){
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left,p,q);
        TreeNode right = lowestCommonAncestor(root.right,p,q);
        if(left != null && right != null){
            return root;
        }
        return left!=null?left:right;
    }
}

时间复杂度:O(N)

空间复杂度:O(N)

核心:递归不考虑全局过程,只考虑边界条件和非边界条件即可

相关推荐
2401_853576502 小时前
C++中的组合模式变体
开发语言·c++·算法
snakeshe10102 小时前
从 MySQL 到 Elasticsearch:构建高性能新闻爬虫的数据存储与搜索体系
java
技术小白菜2 小时前
海康平台通过代理播放视频流
java·java ee
学习3人组2 小时前
Workerman实现 WSS 基于客户端 ID 的精准推送
android·java·开发语言
百结2142 小时前
Nginx性能优化与监控实战
java·nginx·性能优化
jason_renyu2 小时前
Maven 新手完全使用指南(完整版)
java·maven·maven新手指南·maven新手完全使用指南·maven新手使用教程·maven教程
jolimark2 小时前
Spring Boot 集成 Kettle
java·spring boot·后端
云栖笑笑生2 小时前
Java中变量的定义及注意事项
java
像污秽一样2 小时前
算法设计与分析-习题8.2
数据结构·算法·排序算法·dfs·化简