Friday, April 27, 2012

Construct a BST from In-order and Pre-order Traversal Result

[Question]
Construct a BST from in-order and pre-order traversal result.

For example,
Given pre-order traversal [6, 2, 4, 3, 5, 8, 7] and in-order traversal [2, 3, 4, 5, 6, 7, 8], the BST should be
[Analysis]
Pre-order traversal gives out the root of BST as the first element. Based on root, left and right sub-trees can be found in in-order traversal.
As in the example above, because 6 is the first element in pre-order traversal, 6 must be the root element. Then [2, 3, 4, 5] is the left sub-tree, and [7, 8] is the right sub-tree, according to in-order traversal.
             pre-order:  [6, [2, 4, 3, 5], [8, 7]]     in-order: [[2, 3, 4, 5], 6, [7, 8]]
The problem is reduced to (1) re-construct left sub-tree based on pre-order [2, 4, 3, 5] and in-order [2, 3, 4, 5], and (2) re-construct right sub-tree based on pre-order [8, 7] and in-order [7,8].

[Solution]
/*
 * public class BSTNode {
 *       int value;
 *       BSTNode left, right;
 * }
 */

    public static BSTNode constructBST (List<Integer> preOrder, List<Integer> inOrder) {
        assert preOrder.size() == inOrder.size();
        if (preOrder.size() == 0) return null;

        BSTNode node = new BSTNode();
        node.value = preOrder.get(0);

        int index = inOrder.indexOf(preOrder.get(0));
        node.left = constructBST(preOrder.subList(1, index+1), inOrder.subList(0, index));
        node.right= constructBST(preOrder.subList(index+1, preOrder.size()), inOrder.subList(index+1, inOrder.size()));
        return node;
    }  



No comments:

Post a Comment