1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { Map<Integer, Integer> map = new HashMap<>(); public TreeNode buildTree(int[] inorder, int[] postorder) { for (int i = 0; i < inorder.length; i++) { map.put(inorder[i], i); }
return findNode(inorder, 0, inorder.length, postorder, 0, postorder.length); }
public TreeNode findNode(int[] inorder, int inBegin, int inEnd, int[] postorder, int postBegin, int postEnd) { if (inBegin >= inEnd && postBegin >= postEnd ) { return null; }
int rootIndex = map.get(postorder[postEnd - 1]); TreeNode root = new TreeNode(inorder[rootIndex]); int leftLength = rootIndex - inBegin; root.left = findNode(inorder, inBegin, rootIndex, postorder, postBegin, postBegin + leftLength); root.right = findNode(inorder, rootIndex + 1, inEnd, postorder , postBegin + leftLength, postEnd - 1); return root; } }
|