leecode更新

This commit is contained in:
markilue 2023-04-16 21:33:00 +08:00
parent 90237fe746
commit 8eb1d7b2ac
1 changed files with 56 additions and 0 deletions

View File

@ -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;//没找到
}
}