0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swift バイナリツリー②

Posted at

Swift バイナリツリー②

前回のバイナリツリーに挿入する,検索する関数

//挿入

  public func insert(value: T) {
//小さければ左に行く
    if value < self.value {
//if let構文
      if let left = left {
        left.insert(value: value)
      } else {
//値がなければノードを作成し、親ノードを設定する
        left = BinarySearchTree(value: value)
        left?.parent = self
      }
//右に行く場合
    } else {
//if let 構文
      if let right = right {
        right.insert(value: value)
      } else {
//値がなければノードを作成し、親ノードを設定する
        right = BinarySearchTree(value: value)
        right?.parent = self
      }
    }
  }

//検索
  public func search(value: T) -> BinarySearchTree? {
//左をサーチする再帰処理
    if value < self.value {
      return left?.search(value)
    } else if value > self.value {
//右をサーチする再帰処理
      return right?.search(value)
    } else {
      return self  //発見!
    }
  }
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?