Created
February 10, 2015 04:15
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 || postorder == null) | |
return null; | |
if (inorder.length != postorder.length) | |
return null; | |
int len = inorder.length; | |
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); | |
for (int i = 0; i < len; i++) | |
map.put(inorder[i], i); | |
return buildTree(inorder, 0, len - 1, postorder, 0, len - 1, map); | |
} | |
private TreeNode buildTree(int[] inorder, int lo1, int hi1, int[] postorder, int lo2, int hi2, HashMap<Integer, Integer> map) { | |
if (lo1 > hi1) | |
return null; | |
TreeNode node = new TreeNode(postorder[hi2]); | |
int index = map.get(postorder[hi2]); | |
int left = index - lo1, right = hi1 - index; | |
node.left = buildTree(inorder, lo1, index - 1, postorder, lo2, lo2 + left - 1, map); | |
node.right = buildTree(inorder, index + 1, hi1, postorder, lo2 + left, hi2 - 1, map); | |
return node; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment