| 16 | */ |
| 17 | |
| 18 | public class BuildBinaryTree { |
| 19 | int preorderIndex = 0; |
| 20 | Map<Integer, Integer> inorderIndexesMap = new HashMap<>(); |
| 21 | |
| 22 | public TreeNode buildBinaryTree(int[] preorder, int[] inorder) { |
| 23 | // Populate the hash map with the inorder values and their indexes. |
| 24 | for (int i = 0; i < inorder.length; i++) { |
| 25 | inorderIndexesMap.put(inorder[i], i); |
| 26 | } |
| 27 | // Build the tree and return its root node. |
| 28 | return buildSubtree(0, inorder.length - 1, preorder, inorder); |
| 29 | } |
| 30 | |
| 31 | private TreeNode buildSubtree(int left, int right, int[] preorder, int[] inorder) { |
| 32 | // Base case: if no elements are in this range, return None. |
| 33 | if (left > right) { |
| 34 | return null; |
| 35 | } |
| 36 | int val = preorder[preorderIndex]; |
| 37 | // Set 'inorderIndex' to the index of the same value pointed at by |
| 38 | // 'preorderIndex'. |
| 39 | int inorderIndex = inorderIndexesMap.get(val); |
| 40 | TreeNode node = new TreeNode(val); |
| 41 | // Advance 'preorderIndex' so it points to the value of the next |
| 42 | // node to be created. |
| 43 | preorderIndex++; |
| 44 | // Build the left and right subtrees and connect them to the current |
| 45 | // node. |
| 46 | node.left = buildSubtree(left, inorderIndex - 1, preorder, inorder); |
| 47 | node.right = buildSubtree(inorderIndex + 1, right, preorder, inorder); |
| 48 | return node; |
| 49 | } |
| 50 | } |
nothing calls this directly
no outgoing calls
no test coverage detected