kotlin-coding-challenges icon indicating copy to clipboard operation
kotlin-coding-challenges copied to clipboard

Error in solution for binarytree/validate

Open andkrist opened this issue 6 years ago • 2 comments

The solution in binarytree will never validate a right node as long as the left node is present, causing invalid trees with errors further to the right to count as valid.

These tests invalidates the given solution:

    @Test
    fun `Validate invalid BST 1`() {
        // -- -------Tree------------
        //
        //           10
        //          /  \
        //         5    15
        //        /       \
        //       0         20
        //     /  \
        //   -1   999
        // --------------------------

        val node = Node(10)
        node.insert(5)
        node.insert(15)
        node.insert(0)
        node.insert(-1)
        node.insert(20)
        node.left?.left?.right = Node(999)

        isValidSearchBinaryTree(node) shouldEqual false
    }

    @Test
    fun `Validate invalid BST 2`() {
        // -- -------Tree------------
        //
        //           10
        //          /  \
        //         5    15
        //        /       \
        //       0         20
        //                /  \
        //             999    21
        // --------------------------

        val node = Node(10)
        node.insert(5)
        node.insert(15)
        node.insert(0)
        node.insert(20)
        node.insert(21)
        node.right?.right?.left = Node(999)

        isValidSearchBinaryTree(node) shouldEqual false
    }

andkrist avatar Oct 28 '19 19:10 andkrist

Suggesting new solution. This one should work for all types implementing Comparable, and validate all nodes.

private fun <E : Comparable<E>> Node<E>.isValidSearchBinaryTree(min: E? = null, max: E? = null): Boolean {
    if (min != null && data < min) {
        return false
    }
    if (max != null && data > max) {
        return false
    }
    
    return left?.isValidSearchBinaryTree(min, data) ?: true &&
            right?.isValidSearchBinaryTree(data, max) ?: true
}

andkrist avatar Oct 28 '19 19:10 andkrist

thx for the info Can you open PR please?

igorwojda avatar Feb 22 '20 20:02 igorwojda

thx for the contribution. The chellange has been updated.

igorwojda avatar Sep 15 '22 19:09 igorwojda