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

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

相关推荐
cpp_25013 小时前
P1024 [NOIP 2001 提高组] 一元三次方程求解
数据结构·c++·算法·题解·二分答案·洛谷·csp
半瓶榴莲奶^_^4 小时前
jvm java虚拟机
java·jvm
田梓燊9 小时前
力扣:23.合并 K 个升序链表
算法·leetcode·链表
invicinble10 小时前
这里对java的知识体系做一个全域的介绍
java·开发语言·python
wbs_scy10 小时前
【Linux 线程进阶】进程 vs 线程资源划分 + 线程控制全详解
java·开发语言
re林檎10 小时前
算法札记——4.27
算法
ss27310 小时前
食谱推荐系统功能测试如何写?
java·数据库·spring boot·功能测试
AI人工智能+电脑小能手10 小时前
【大白话说Java面试题】【Java基础篇】第15题:JDK1.7中HashMap扩容为什么会发生死循环?如何解决
java·开发语言·数据结构·后端·面试·哈希算法
数据牧羊人的成长笔记11 小时前
逻辑回归与Softmax回归
算法·回归·逻辑回归
try2find11 小时前
打印ascii码报错问题
java·linux·前端