1.根据中序和前序
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || preorder.length == 0 || inorder == null || inorder.length == 0) {
return null;
}
return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
}
public TreeNode build(int[] preorder, int leftP, int rightP, int[] inorder, int leftI, int rightI) {
if (leftP > rightP || leftI > rightI) {
return null;
}
TreeNode root = new TreeNode(preorder[leftP]);
int indexInInOrder = findRootIndexInOrder(inorder, leftI, rightI, root.val);
int offset = indexInInOrder - leftI - 1;
TreeNode left = build(preorder, leftP + 1, leftP + 1 + offset, inorder, leftI, indexInInOrder - 1);
TreeNode right = build(preorder, leftP + offset + 2, rightP, inorder, indexInInOrder + 1, rightI);
root.left = left;
root.right = right;
return root;
}
public int findRootIndexInOrder(int[] inorder, int left, int right, int target) {
int result = 0;
for (int i = left; i <= right; i++) {
if (inorder[i] == target) {
result = i;
break;
}
}
return result;
}
}
offset很重要,一步到位
2.根据中序和后序
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || inorder.length == 0 || postorder == null || postorder.length == 0) {
return null;
}
return build(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}
public TreeNode build(int[] inorder, int leftI, int rightI, int[] postorder, int leftP, int rightP) {
if (leftI > rightI || leftP > rightP) {
return null;
}
TreeNode root = new TreeNode(postorder[rightP]);
int indexInInOrder = findRootIndexInOrder(inorder, leftI, rightI, root.val);
int offset = indexInInOrder - 1 - leftI;
TreeNode left = build(inorder, leftI, indexInInOrder - 1, postorder, leftP, leftP + offset);
TreeNode right = build(inorder, indexInInOrder + 1, rightI, postorder, leftP + offset + 1, rightP - 1);
root.left = left;
root.right = right;
return root;
}
public int findRootIndexInOrder(int[] inorder, int left, int right, int target) {
int result = 0;
for (int i = left; i <= right; i++) {
if (inorder[i] == target) {
result = i;
break;
}
}
return result;
}
}