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

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

相关推荐
Dicky-_-zhang2 小时前
系统容量规划与压测实战:从1万到100万QPS的科学扩容
java·jvm
BirdenT2 小时前
20260519紫题训练
c++·算法
csdn_aspnet7 小时前
C语言 Lomuto分区算法(Lomuto Partition Algorithm)
c语言·开发语言·算法
Dicky-_-zhang7 小时前
消息队列Kafka/RocketMQ选型与高可用架构:从单体到100万TPS的演进
java·jvm
晨曦中的暮雨7 小时前
4.15腾讯 CSIG云服务产线 一面
java·开发语言
fake_ss1987 小时前
AI时代学习全栈项目开发的新范式
java·人工智能·学习·架构·个人开发·学习方法
谙弆悕博士7 小时前
【附C源码】从零实现C语言堆数据结构:原理、实现与应用
c语言·数据结构·算法··数据结构与算法
茉莉玫瑰花茶8 小时前
工作流的常见模式 [ 1 ]
java·服务器·前端
未若君雅裁8 小时前
Spring AOP、日志切面与声明式事务原理
java·后端·spring
No8g攻城狮8 小时前
【人大金仓】wsl2+ubuntu22.04安装人大金仓数据库V9
java·数据库·spring boot·非关系型数据库