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

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

相关推荐
Deep-w5 小时前
【MATLAB】基于离散 LQR 的车辆横向轨迹跟踪控制方法研究
开发语言·算法·matlab
2601_961194025 小时前
考研资料电子版|去哪找|网盘
java·c语言·c++·python·考研·php
Peter·Pan爱编程5 小时前
23. 算法库:用算法代替手写循环
c++·人工智能·算法
于先生吖5 小时前
前后端分离二手商城开发,质检登记、回收回款整套业务源码部署教程
java·开发语言·uni-app
小锋java12345 小时前
分享一套锋哥原创的基于LangChain4j的RAG医疗健康知识智能问答系统(SpringBoot4+Vue3+Ollama)
java·人工智能
小欣加油6 小时前
leetcode2161 根据给定数字划分数组
数据结构·c++·算法·leetcode·职场和发展
程序员晨曦6 小时前
Java 并发修仙传:ThreadLocal 从“闭关修炼”到“走火入魔”的救赎之路
java·开发语言
AIGS0016 小时前
探索向量空间JBoltAI:工业企业数智化升级的基础设施
java·人工智能·人工智能ai大模型应用
雨落在了我的手上6 小时前
Java数据结构(四):List的介绍
数据结构
大都督会赢的6 小时前
数据结构(2)--单链表
数据结构