/** * File: build_tree.java * Created Time: 2023-07-17 * Author: krahets (krahets@163.com) */ package chapter_divide_and_conquer; import utils.*; import java.util.*; public class build_tree { /* 构建二叉树:分治 */ static TreeNode dfs(int[] preorder, Map inorderMap, int i, int l, int r) { // 子树区间为空时终止 if (r - l < 0) return null; // 初始化根节点 TreeNode root = new TreeNode(preorder[i]); // 查询 m ,从而划分左右子树 int m = inorderMap.get(preorder[i]); // 子问题:构建左子树 root.left = dfs(preorder, inorderMap, i + 1, l, m - 1); // 子问题:构建右子树 root.right = dfs(preorder, inorderMap, i + 1 + m - l, m + 1, r); // 返回根节点 return root; } /* 构建二叉树 */ static TreeNode buildTree(int[] preorder, int[] inorder) { // 初始化哈希表,存储 inorder 元素到索引的映射 Map inorderMap = new HashMap<>(); for (int i = 0; i < inorder.length; i++) { inorderMap.put(inorder[i], i); } TreeNode root = dfs(preorder, inorderMap, 0, 0, inorder.length - 1); return root; } public static void main(String[] args) { int[] preorder = { 3, 9, 2, 1, 7 }; int[] inorder = { 9, 3, 1, 2, 7 }; System.out.println("前序遍历 = " + Arrays.toString(preorder)); System.out.println("中序遍历 = " + Arrays.toString(inorder)); TreeNode root = buildTree(preorder, inorder); System.out.println("构建的二叉树为:"); PrintUtil.printTree(root); } }