【问题标题】:Nilling out optional not working in BST implementation剔除在 BST 实施中不起作用的可选选项
【发布时间】:2017-09-03 13:24:13
【问题描述】:

我正在实现一个 BST 并使用 remove() 函数,问题是当我尝试清除节点以删除即当前节点时,当我打印树结构时它仍然存在。

class Node<T : Comparable> {

    var value: T
    var left: Node<T>?
    var right: Node<T>?

    init(_ value:T) {
      self.value = value
    }
}

func remove(_ value:T) {

    var current: Node<T>? = root

    while let root = current {

        if value == root.value {
            if let _ = root.left, let right = root.right {

                let minValue = getMinValue(right)
                root.value = minValue
                remove(minValue)
            } else if let left = root.left {

                root.value = left.value
                root.left = nil
            } else if let right = root.right {

                root.value = right.value
                root.left = nil
            } else {
                //This doesn't remove the reference completely
                current = nil
            }

        } else if value > root.value {
            current = root.right
        } else {
            current = root.left
        }
    }
}

我的打印函数仍然打印出我在上一个函数中删除的节点

private func printTree(_ node:Node<T>?){

    guard let root = node else {
        return
    }
    print(root.value)
    printTree(root.right)
    printTree(root.left)
}

【问题讨论】:

    标签: swift swift3 binary-tree binary-search-tree optional


    【解决方案1】:

    不幸的是,您只是将局部变量 current 设置为 nil。 current 的父节点仍然具有您要删除的节点的引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多