diff --git a/Leecode/src/main/java/com/markilue/leecode/hot100/second/T46_105_BuildTree.java b/Leecode/src/main/java/com/markilue/leecode/hot100/second/T46_105_BuildTree.java new file mode 100644 index 0000000..5c50ef2 --- /dev/null +++ b/Leecode/src/main/java/com/markilue/leecode/hot100/second/T46_105_BuildTree.java @@ -0,0 +1,56 @@ +package com.markilue.leecode.hot100.second; + +import com.markilue.leecode.tree.TreeNode; + +/** + * @BelongsProject: Leecode + * @BelongsPackage: com.markilue.leecode.hot100.second + * @Author: marklue + * @CreateTime: 2023/4/16 11:15 + * @Description: TODO 力扣105 根据前序遍历和中序遍历构造树 + * @Version: 1.0 + */ +public class T46_105_BuildTree { + + int index = 0; + + public TreeNode buildTree(int[] preorder, int[] inorder) { + + return buildChild(preorder, inorder, 0, inorder.length - 1); + + } + + public TreeNode buildChild(int[] preorder, int[] inorder, int inStart, int inEnd) { + if (inStart > inEnd) { + return null; + } + TreeNode root = new TreeNode(preorder[index]); + index++; + int in = findIndex(inorder, inStart, inEnd, root.val); + root.left = buildChild(preorder, inorder, inStart, in - 1); + root.right = buildChild(preorder, inorder, in + 1, inEnd); + return root; + + } + + /** + * 在start和end的范围中寻找target + * + * @param inorder + * @param start + * @param end + * @param target + * @return + */ + public int findIndex(int[] inorder, int start, int end, int target) { + + while (start < end) { + if (inorder[start] == target) { + return start; + } + start++; + } + return -1;//没找到 + + } +}