题目
链接
题解
import java.util.Map;
import java.util.HashMap;
/**
* Definition for a binary tree node.
* 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;
* }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
// 哈希表,k:中序遍历的节点,v:中序遍历的下标
Map<Integer, Integer> hash = new HashMap<>(inorder.length);
for (int i = 0; i < inorder.length; i++) {
hash.put(inorder[i], i);
}
return build(preorder, inorder, 0, 0, inorder.length - 1, hash);
}
private TreeNode build(int[] preorder, int[] inorder, int rootPreorderIndex, int inBegin, int inEnd, Map<Integer, Integer> hash) {
if (inBegin == inEnd) {
return new TreeNode(inorder[inBegin], null, null);
}
int rootValue = preorder[rootPreorderIndex];
// 找根节点在中序遍历中的下标
int rootInorderIndex = hash.get(rootValue);
// 递归左子树
TreeNode left = null;
if (inBegin <= rootInorderIndex - 1 && rootPreorderIndex + 1 <= preorder.length - 1) {
left = build(preorder, inorder, rootPreorderIndex + 1, inBegin, rootInorderIndex - 1, hash);
}
// 递归右子树
TreeNode right = null;
if (rootInorderIndex + 1 <= inEnd) {
// 计算右子树根节点在前序遍历中的下标,计算公式:当前根节点在前序遍历中的下标 + 左子树节点个数
// 左子树节点个数计算公式:当前根节点在中序遍历中的下标 - 中序遍历起始下标 + 1
int rightRootPreorderIndex = rootPreorderIndex + (rootInorderIndex - inBegin) + 1;
right = build(preorder, inorder, rightRootPreorderIndex, rootInorderIndex + 1, inEnd, hash);
}
return new TreeNode(preorder[rootPreorderIndex], left, right);
}
private int seach(int[] src, int target, int start, int end) {
for (int i = start; i <= end; i++) {
if (src[i] == target) {
return i;
}
}
return -1;
}
}