1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { return buildTree(inorder, 0, inorder.length, postorder, postorder.length - 1); }
public TreeNode buildTree(int[] inorder, int start, int end, int[] postorder, int rootIdx) { if (start >= end) { return null; }
if (start == end - 1) { return new TreeNode(inorder[start]); }
TreeNode root = new TreeNode(postorder[rootIdx]);
int rootIdxInOrder = start; for (int idx = start; idx < end; idx++) { if (inorder[idx] == root.val) { rootIdxInOrder = idx; break; } }
TreeNode leftNode = buildTree(inorder, start, rootIdxInOrder, postorder, rootIdx - (end - rootIdxInOrder));
TreeNode rightNode = buildTree(inorder, rootIdxInOrder + 1, end, postorder, rootIdx - 1);
root.left = leftNode; root.right = rightNode; return root; } }
|