почему функция при вызове в результате выдает NullPointerException?

реализации функции remove() для BinarySearchTree.

Тест: на вход подается бинарное дерево поска в виде массива [65, 21, 69, 42, 43, 0, 90, 49, 72, 78, 58, 4, 54, 46, 98, 35, 28], нужно удалить узел со значение = 3.

Почему функция findParent() при вызове в результате выдает NullPointerException?

  override fun remove(element: T): Boolean {
        fun findParent(begin: Node<T>): Node<T>? {
            if (element < begin.value) {
                val left = begin.left ?: return null
                if (left.value == element) return begin
                return findParent(left)
            }
            if (element > begin.value) {
                val right = begin.right ?: return null
                if (right.value == element) return begin
                return findParent(right)
            }
            throw IllegalStateException()
        }

        var closest = find(element) ?: return false
        val parent = findParent(this.root!!)
        //нет потомков
        if (closest.right == null && closest.left == null) {
            if (parent?.value!! > closest.value)
                parent.left = null
            if (parent.value < closest.value)
                parent.right = null
        }
        // есть один потомок
        if (closest.right == null || closest.left == null) {
            if (closest.left != null) {
                if (parent?.value!! > closest.value)
                    parent.left = closest.left
                if (parent.value < closest.value)
                    parent.right = closest.left
                closest.left = null
            }
            if (closest.right != null) {
                if (parent?.value!! > closest.value)
                    parent.left = closest.right
                if (parent.value < closest.value)
                    parent.right = closest.right
                closest.right = null
            }
        }
        // два потомка
        if (closest.right != null && closest.left != null) {
            var root = closest.right
            var parentRoot: Node<T>? = null
            while (root?.left != null) {
                parentRoot = root
                root = root.left
            }
            closest = root!!
            root = closest.right
            while (root?.value != parentRoot?.value)
                root = root?.left
            root?.left = null
        }
        size--
        return true
    }

Ответы (0 шт):