2017-09-03 5 views
1

BSTを実装してremove()関数を処理しています。ノードを削除しないと問題が発生します。BSTの実装では機能しないオプションのNothingを返します。

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

答えて

2

残念ながらあなただけのnilにローカル変数currentを設定を削除したノードを出力します。 の親ノードには、引き続き削除しようとしているノードの参照があります。

+0

これは、ありがとう! –

関連する問題