Problem
Given the Pre-order tranversal & In-order tranversal, retrieve the original tree.
Solution
Divide-and-conquer
- Divide the original tree into root, left subtree, right subtree.
- Do this recursively for every subtree.
Example
Pre-order: 3, 4, 0, 1, 5, 2, 6, 7
In-order: 4, 3, 1, 5, 0, 2, 7, 6
- From the pre-order, we conclude 3 is the root
- Locate 3 in the in-order.
- Left subtree contains 4 (leaf node)
- Right subtree contains 1, 5, 0, 2, 7, 6
- Inorder-based-representation: [4] 3 [1 5 0 2 7 6]
Visualization:
3
/ \
4 [1 5 0 2 7 6]
- Look at the right subtree [1 5 0 2 7 6]
- Its pre-order traversal: [0 1 5 2 6 7]
- root is 0, left subtree [1 5], right subtree [2 6 7]
- partial representation: [1 5] 0 [2 7 6]
- the whole tree: [4] 3 [ [1 5] 0 [2 7 6] ]
Visualization:
3
/ \
4 0
/ \
[1 5] [2 7 6]
- Look at left subtree [1 5]
- Pre-order traversal: [1 5]
- root is 1, left subtree empty, right subtree [5]
- partial representation: 1 [5]
- the whole tree: [4] 3 [ [ 1 [5] ] 0 [2 7 6] ]
Visualization:
3
/ \
4 0
/ \
1 [2 7 6]
\
5
- Look at right subtree [2 7 6]
- Pre-order traversal: [2 6 7]
- root is 2, left subtree empty, right subtree [7 6]
- partial representation: 2 [7 6]
- the the whole tree: [4] 3 [ [ 1 [5] ] 0 [ 2 [7 6] ] ]
Visualization:
3
/ \
4 0
/ \
1 2
\ \
5 [7 6]
- Look at right subtree [7 6]
- Pre-order traversal: [6 7]
- root is 6, left subtree [7], right subtree empty
- partial representation: [7] 6
- the the whole tree: [4] 3 [ [ 1 [5] ] 0 [ 2 [ [7] 6 ] ] ]
Visualization:
3
/ \
4 0
/ \
1 2
\ \
5 6
/
7