LintCode 72. 中序遍历和后序遍历树构造二叉树

/**
* Definition of TreeNode:
* public class TreeNode {
*     public int val;
*     public TreeNode left, right;
*     public TreeNode(int val) {
*         this.val = val;
*         this.left = this.right = null;
*     }
* }
*/

public class Solution {
/**
* @param inorder: A list of integers that inorder traversal of a tree
* @param postorder: A list of integers that postorder traversal of a tree
* @return: Root of a tree
*/
public TreeNode buildTree(int[] inorder, int[] postorder) {
TreeNode root = null;
int[] inorderLeft, inorderRight, postorderLeft, postOrderRight;
int rootIndex = 0;
if (inorder != null && inorder.length > 0 && postorder != null && postorder.length > 0) {
root = new TreeNode(postorder[postorder.length - 1]);
for (int i = 0; i < inorder.length; i++) {
if (root.val == inorder[i]) {
break;
}
rootIndex++;
}

inorderLeft = new int[rootIndex];
postorderLeft = new int[rootIndex];
for (int i = 0; i < rootIndex; i++) {
inorderLeft[i] = inorder[i];
postorderLeft[i] = postorder[i];
}

inorderRight = new int[inorder.length - rootIndex - 1];
postOrderRight = new int[postorder.length - rootIndex - 1];
for (int i = rootIndex + 1; i < postorder.length; i++) {
inorderRight[i - rootIndex - 1] = inorder[i];
postOrderRight[i - rootIndex - 1] = postorder[i - 1];
}

root.left = buildTree(inorderLeft, postorderLeft);
root.right = buildTree(inorderRight, postOrderRight);
}
return root;
}
}