萤火小屋

优律的知识库

  • 首页
  • 归档
  • 分类
  • 标签
  • 留言
  • 关于

  • 搜索
消息队列 RabbitMQ Redis 双指针 力扣 动态代理 Git YAML SpringBoot SpringMVC 回溯算法 分治算法 归并排序 快排 手撕 事务 MySQL索引 MySQL 小技巧 Spring Framework Spring 动态规划 Linux Android 贪心算法 操作系统 进程调度模拟 IPv6 数据库 计算机组成原理 计算机基础 栈 Java 静态路由 路由器 交换机 数字通信 网络工程 计算机网络 Web http 大学学习技巧 程序设计 算法

力扣第105题-从前序与中序遍历序列构造二叉树

发表于 2023-08-02 | 分类于 力扣刷题 | 0 | 阅读次数 28

题目
链接

题解

import java.util.Map;
import java.util.HashMap;
/**
 * 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 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        // 哈希表,k:中序遍历的节点,v:中序遍历的下标
        Map<Integer, Integer> hash = new HashMap<>(inorder.length);
        for (int i = 0; i < inorder.length; i++) {
            hash.put(inorder[i], i);
        }
        return build(preorder, inorder, 0, 0, inorder.length - 1, hash);
    }

    private TreeNode build(int[] preorder, int[] inorder, int rootPreorderIndex, int inBegin, int inEnd, Map<Integer, Integer> hash) {
        if (inBegin == inEnd) {
            return new TreeNode(inorder[inBegin], null, null);
        }
        int rootValue = preorder[rootPreorderIndex];
        // 找根节点在中序遍历中的下标
        int rootInorderIndex = hash.get(rootValue);
        // 递归左子树
        TreeNode left = null;
        if (inBegin <= rootInorderIndex - 1 && rootPreorderIndex + 1 <= preorder.length - 1) {
            left = build(preorder, inorder, rootPreorderIndex + 1, inBegin, rootInorderIndex - 1, hash);
        }
        // 递归右子树
        TreeNode right = null;
        if (rootInorderIndex + 1 <= inEnd) {
            // 计算右子树根节点在前序遍历中的下标,计算公式:当前根节点在前序遍历中的下标 + 左子树节点个数
            // 左子树节点个数计算公式:当前根节点在中序遍历中的下标 - 中序遍历起始下标 + 1
            int rightRootPreorderIndex = rootPreorderIndex + (rootInorderIndex - inBegin) + 1;
            right = build(preorder, inorder, rightRootPreorderIndex, rootInorderIndex + 1, inEnd, hash);
        }
        return new TreeNode(preorder[rootPreorderIndex], left, right);
    }

    private int seach(int[] src, int target, int start, int end) {
        for (int i = start; i <= end; i++) {
            if (src[i] == target) {
                return i;
            }
        }
        return -1;
    }

}
# 算法 # 程序设计 # 力扣
力扣第103题-二叉树的锯齿形层序遍历
  • 文章目录
  • 站点概览
优律

优律

优律的知识库

125 日志
20 分类
44 标签
E-mail Twitter Instagram
Links
  • CZLisyx - 浮生志
  • Vedfolnir
0%
© 2019 — 2023 萤火小屋——优律的博客网站
网站已勉强运行 
Halo博客系统技术支持