Find the last element from inOrder, Will get the length of subTrees.
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || postorder == null) return null;
if (inorder.length == 0 || postorder.length == 0) return null;
return buildTree(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
}
private TreeNode buildTree(int[] inorder, int start1, int end1, int[] postorder, int start2, int end2) {
if (start1 > end1 || start2 > end2) return null;
int currentValue = postorder[end2];
TreeNode currRoot = new TreeNode(currentValue);
int k = start1;
for (; k < inorder.length; k++) {
if (inorder[k] == currentValue) break;
}
currRoot.left = buildTree(inorder, start1, k-1, postorder, start2, end2-end1+k-1);
currRoot.right = buildTree(inorder, k+1, end1, postorder, end2-end1+k, end2-1);
return currRoot;
}
No comments:
Post a Comment