【算法二十五】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)

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

相关推荐
她说..18 小时前
Java 对象相关高频面试题
java·开发语言·spring·java-ee
汀、人工智能18 小时前
[特殊字符] 第21课:最长有效括号
数据结构·算法·数据库架构·图论·bfs·最长有效括号
Boop_wu19 小时前
[Java 算法] 字符串
linux·运维·服务器·数据结构·算法·leetcode
庞轩px19 小时前
深入理解 sleep() 与 wait():从基础到监视器队列
java·开发语言·线程··wait·sleep·监视器
故事和你9119 小时前
洛谷-算法1-2-排序2
开发语言·数据结构·c++·算法·动态规划·图论
Fcy64820 小时前
算法基础详解(三)前缀和与差分算法
算法·前缀和·差分
皮皮林55120 小时前
面试官:ZSet 的底层实现是什么?
java
kvo7f2JTy20 小时前
基于机器学习算法的web入侵检测系统设计与实现
前端·算法·机器学习
码云数智-大飞20 小时前
C++ RAII机制:资源管理的“自动化”哲学
java·服务器·php
2601_9498165820 小时前
Spring+Quartz实现定时任务的配置方法
java