最小二叉搜索树的Swift实现正在进行无限递归

时间:2017-03-31 05:35:47

标签: swift algorithm recursion

最后一天,我试图弄清楚为什么这个函数会进行无限递归。

我已经在Python中实现了相同的逻辑,并且它可以完美地工作。我甚至只尝试左和右只有递归调用和循环停止但是当一起完成时这将进行无限调用。

public class BSTNode<T: Comparable> {
    var data: T

    var left: BSTNode<T>?
    var right: BSTNode<T>?

    init(data: T) {
        self.data = data
    }

}



func minimalTree(startIndex: Int, endIndex: Int, array: [Int]) -> BSTNode<Int>? {

    if startIndex >= endIndex {
        return nil
    }

    print("start \(startIndex)")
    print("end \(endIndex)")


    let midIndex = Int((startIndex + endIndex / 2))
    let midElement = array[midIndex]
    let root = BSTNode(data: midElement)

    root.left = minimalTree(startIndex: startIndex, endIndex: midIndex - 1, array: array)
    root.right = minimalTree(startIndex: midIndex + 1, endIndex: endIndex, array: array)

    return root
}

func minimalTreeTest() {

    let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


    _ = minimalTree(startIndex: 0, endIndex: array.count - 1, array: array)
}

0 个答案:

没有答案