Professional Documents
Culture Documents
Interview Camp
Level: Hard
Given inorder and preorder traversals of a binary tree, reconstruct the binary tree.
Questions to Clarify:
Q. Can we assume that the traversals are in the form of an array of integers?
A. Yes
Q. Are there duplicates in the traversal?
A. No.
Solution:
There are few reconstruction questions asked. However, it is a concept you should understand.
The idea is that you have a traversal of a tree, e.g, [1,3,5,6,8]. You will either be asked
to reconstruct a tree from the traversal, or asked if a traversal is possible.
For a binary tree, reconstruction is possible if you’re given an inorder traversal and
one of preorder and postorder traversals. The reasoning is simple: With a preorder traversal,
the first node is the root. We’ve now identified the root of the tree.
For example:
Preorder: 4 2 1 3 6 5 7
Inorder : 1 2 3 4 5 6 7
In the above traversals, we know 4 is the root because it is first in preorder.
With the inorder traversal, we can find the root, and identify all the nodes in the
right tree and left tree of the root.
Above, we can deduce that [1 2 3] are in the left subtree of 4 and [5 6 7] are in the
right subtree.
This applied recursively can construct the entire tree. We apply the same to the left and right subtrees.
These subtrees are just subarrays of the original traversals.
Left Subtree:
Preorder: 4 [2 1 3] 6 5 7
Inorder : [1 2 3] 4 5 6 7
Right Subtree:
Preorder: 4 2 1 3 [6 5 7]
Inorder : 1 2 3 4 [5 6 7]
Another caveat: This works only if the traversals don’t have duplicates. If there are
duplicate values, we don’t know which root element is the actual root.
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
Pseudocode:
// create tree form the following subarrays - preorder[pre-start..pre-end]
// and inorder[in-start..in-end]
construct(preorder, pre-start, pre-end, inorder, in-start, in-end, inorder-map)
root-value = first element of preorder subarray
root-node = new node with value root-value
i = index of root-value in inorder subarray (using inorder-map)
return root-node
Test Cases:
Edge Cases: Empty tree
Base Cases: tree with one node, tree with 2 nodes (left/right subtree)
Regular Cases: trees with multiple subtrees, one subtree (left/right)
Time Complexity: O(n) worse case, if the tree was like a chain
Space Complexity: O(n) worse case, if the tree was like a chain
public Node buildTree(int[] preorder, int[] inorder) {
HashMap<Integer, Integer> inorderMap = getInorderMap(inorder);
return construct(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1,
inorderMap);
}
public Node construct(int[] preorder, int preStart, int preEnd, int[] inorder,
int inStart, int inEnd, HashMap<Integer, Integer> inorderMap){
if(preStart > preEnd || inStart > inEnd){
return null;
}
© 2017 Interview Camp (interviewcamp.io)
Interview Camp
/*
* Helper code. Implement only if the interviewer wants you to.
*/
© 2017 Interview Camp (interviewcamp.io)