题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { private Map<Integer, Integer> inMap = new HashMap<>(); /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param preOrder int整型一维数组 * @param vinOrder int整型一维数组 * @return TreeNode类 */ public TreeNode reConstructBinaryTree (int[] preOrder, int[] vinOrder) { // write code here for (int i = 0; i < vinOrder.length; i++) { inMap.put(vinOrder[i], i); } return buildTree(preOrder, vinOrder, 0, preOrder.length - 1, 0, vinOrder.length - 1); } private TreeNode buildTree(int[] preOrder, int[] vinOrder, int preStart, int preEnd, int inLeft, int inEnd) { if (preEnd < preStart) { return null; } int current = preOrder[preStart]; TreeNode root = new TreeNode(current); int currentIndex = inMap.get(current); int leftLeng = currentIndex - inLeft; root.left = buildTree(preOrder, vinOrder, preStart + 1, preStart + leftLeng, inLeft, currentIndex - 1); root.right = buildTree(preOrder, vinOrder, preStart + leftLeng + 1, preEnd, currentIndex + 1, inEnd); return root; } }