Nilling out可选不能在BST实现中工作

问题描述:

我正在实现一个BST并且正在执行remove()函数,问题是当我尝试清空节点以删除即当前节点时,它在打印树结构时仍然存在。Nilling out可选不能在BST实现中工作

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) 
} 

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

+0

就是这样,谢谢! –