Pages

Sunday 3 February 2013

Trim a given BST based on Min and Max values

How do you think about this problem recursively. First think about the traversals. It cannot be pre order because you have to return the root. So you need the computation of the left subtree and the right subtree done when you return the values. Hence, it has to be post order traversal. Now, since you know the kind of traversal, think of a recursive solution. Suppose you apply your trim function to the left subtree and the right subtree. Now you have the solutions of the left subtree and the right subtree and they satisfy the min and the max criterion. You are now only left to check the min and the max criterion with the root. Now, write down the code.

TreeNode trim(TreeNode node, int min, int max) {
        if(node == null) return node;
        node.left = trim(node.left, min, max);
        node.right = trim(node.right, min, max);
        if(node.data < max and node.data > min) return node;
        else if(node.data < min) return node.right;
        else if(node.data > max) return node.left;


}

1 comment:

  1. Wrong answer. See for below tree and range [1,8].

    6
    / \
    3 8
    / \ / \
    1 5 7 9
    \ /
    2 4

    ReplyDelete