1 Java AC
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || preorder.length == 0) {
return null;
}
if (inorder == null || inorder.length == 0) {
return null;
}
int len1 = preorder.length - 1;
int len2 = inorder.length - 1;
if (len1 != len2) {
return null;
}
return dfs(preorder, inorder, 0, len2, 0);
}
private TreeNode dfs(int[] preorder, int[] inorder, int low,
int high, int index) {
if (low > high) {
return null;
}
TreeNode node = new TreeNode(preorder[index]);
if (low == high) {
return node;
}
int pos = searchInsert(inorder, preorder[index], low, high);
node.left = dfs(preorder, inorder, low, pos - 1, index + 1);
node.right = dfs(preorder, inorder, pos + 1, high, index + 1 + (pos - low));
return node;
}
private int searchInsert(int[] array, int t, int low, int high) {
int pos = 0;
for (int i = low; i <= high; i++) {
if (array[i] == t) {
pos = i;
break;
}
}
return pos;
}
}
2 Java AC
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || inorder.length == 0) {
return null;
}
if (postorder == null || postorder.length == 0) {
return null;
}
int len1 = inorder.length - 1;
int len2 = postorder.length - 1;
if (len1 != len2) {
return null;
}
return dfs(inorder, postorder, 0, len1, len2);
}
private TreeNode dfs(int[] inorder, int[] postorder, int low,
int high, int index) {
if (low > high) {
return null;
}
TreeNode node = new TreeNode(postorder[index]);
if (low == high) {
return node;
}
int pos = searchInsert(inorder, postorder[index], low, high);
node.left = dfs(inorder, postorder, low, pos - 1, index - 1 - (high - pos));
node.right = dfs(inorder, postorder, pos + 1, high, index - 1);
return node;
}
private int searchInsert(int[] array, int t, int low, int high) {
int pos = 0;
for (int i = low; i <= high; i++) {
if (array[i] == t) {
pos = i;
break;
}
}
return pos;
}
}