【LeetCodehot100】T114:二叉树展开为链表 T105:从前序与中序遍历构造二叉树

T114:二叉树展开为链表

题目要求:

给你二叉树的根结点 root ,请你将它展开为一个单链表:

展开后的单链表应该同样使用 TreeNode ,其中 right 子指针指向链表中下一个结点,而左子指针始终为 null 。

展开后的单链表应该与二叉树 先序遍历 顺序相同。

核心思路

前序遍历顺序+指针重排

具体操作:

  1. 先展开左子树
  2. 再展开右子树
  3. 把左子树移到右边
  4. 把原右子树接到末尾

代码实现

java 复制代码
public void flatten(TreeNode root) {
    if (root == null) return;

    // 1️⃣ 递归展开左右子树
    flatten(root.left);
    flatten(root.right);

    // 2️⃣ 保存原右子树
    TreeNode right = root.right;

    // 3️⃣ 左子树移到右边
    root.right = root.left;
    root.left = null;

    // 4️⃣ 找右链尾节点
    TreeNode cur = root;
    while (cur.right != null) {
        cur = cur.right;
    }

    // 5️⃣ 接上原右子树
    cur.right = right;
}

本题感悟

掌握前序遍历顺序+指针重排的具体流程

  1. 先展开左子树
  2. 再展开右子树
  3. 把左子树移到右边
  4. 把原右子树接到末尾

T105:从前序与中序遍历构造二叉树

题目要求:

给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

核心思路

前序遍历

根 → 左 → 右

作用:

确定"根节点"
中序遍历

左 → 根 → 右

作用:

划分左右子树
前序找根,中序分左右,递归构建

思路

1️⃣ 用 preorderpreL 找到根

2️⃣ 在 inorder 中找到根的位置 index

3️⃣ 计算左子树大小 leftSize

4️⃣ 划分左右子树范围

5️⃣ 递归构建左右子树

代码实现

java 复制代码
class Solution {

    Map<Integer, Integer> map = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {

        // 建立中序索引
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }

        return build(preorder, 0, preorder.length - 1,
                     inorder, 0, inorder.length - 1);
    }

    private TreeNode build(int[] preorder, int preL, int preR,
                           int[] inorder, int inL, int inR) {

        if (preL > preR) return null;

        // 1️⃣ 根节点
        int rootVal = preorder[preL];
        TreeNode root = new TreeNode(rootVal);

        // 2️⃣ 找中序位置
        int index = map.get(rootVal);

        // 3️⃣ 左子树大小
        int leftSize = index - inL;

        // 4️⃣ 左子树
        root.left = build(preorder, preL + 1, preL + leftSize,
                          inorder, inL, index - 1);

        // 5️⃣ 右子树
        root.right = build(preorder, preL + leftSize + 1, preR,
                           inorder, index + 1, inR);

        return root;
    }
}
相关推荐
Resean022312 小时前
Spring 源码分析(二)配置类的解析与扫描
java·后端·spring
小毛球.12 小时前
第 3 篇:IDEA 最新版下载与完整安装教程(Mac)
java·macos·intellij-idea·idea
罗西的思考14 小时前
【轻量化复刻大模型 / KIMI K3】Muon 优化器及 训练系统
人工智能·算法·机器学习
Misnearch14 小时前
ScheduledExecutorService
java·线程池
ashiho15 小时前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口
数据工匠老o15 小时前
数据库没死,业务卡住了:行锁等待、元数据锁、长事务的排查路径
数据库·算法·架构
黑客笔记15 小时前
安全态势感知中的资产失陷排名思考
人工智能·算法·网络安全
T_Wizard15 小时前
AI 回复为什么要转圈 3 秒才「啪」一下全出来?把流式输出拆开看,顺便踩了 6 个坑
java·ai编程
CoderYanger16 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第二弹)
java·数据库·面试·职场和发展·java-ee·tomcat·mybatis