105_从前序与中序遍历序列构造二叉树
package 二叉树.BT; import java.awt.HeadlessException; import java.util.HashMap; import java.util.Map; /** * https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ * * @author Huangyujun * */ public class _105_从前序与中序遍历序列构造二叉树 { 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; } } /** * preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] * 前序特点:第一个便是根结点(知道根比较快),中序:左 根 右 * 前序提供的根结点, 中序不断地划分成左子树、右子树 * @param preorder * @param inorder * @return */ //定义一个 map,键值对,【值, 位置】 Map<Integer, Integer> map = new HashMap<>(); int[] inorder; int[] preorder; int pre_id = 0; public TreeNode buildTree(int[] preorder, int[] inorder) { this.preorder = preorder; this.inorder = inorder; int n = inorder.length; for(int i = 0; i < n; i++) { map.put(inorder[i], i); } return helper(0, n - 1); } //构建的helper(表示一棵树的范围) public TreeNode helper(int left, int right) { if(left > right) return null; int rootVal = preorder[pre_id]; //创建根结点 TreeNode root = new TreeNode(rootVal); //下标++ ,方便下次拿到左子树的根结点 pre_id++; //获取根在中序的位置,将分成两个树 int index = map.get(rootVal); //左子树 root.left = helper(left, index - 1); //右子树 root.right = helper(index + 1, right); return root; } }