iOS二叉树算法

TreeNode是系统类,可以模拟二叉树

let tree = TreeNode(value: "beverages")

let hotNode = TreeNode(value: "hot")
let coldNode = TreeNode(value: "cold")

let teaNode = TreeNode(value: "tea")
let coffeeNode = TreeNode(value: "coffee")
let chocolateNode = TreeNode(value: "cocoa")

let blackTeaNode = TreeNode(value: "black")
let greenTeaNode = TreeNode(value: "green")
let chaiTeaNode = TreeNode(value: "chai")

let sodaNode = TreeNode(value: "soda")
let milkNode = TreeNode(value: "milk")

let gingerAleNode = TreeNode(value: "ginger ale")
let bitterLemonNode = TreeNode(value: "bitter lemon")

tree.addChild(hotNode)
tree.addChild(coldNode)

hotNode.addChild(teaNode)
hotNode.addChild(coffeeNode)
hotNode.addChild(chocolateNode)

coldNode.addChild(sodaNode)
coldNode.addChild(milkNode)

teaNode.addChild(blackTeaNode)
teaNode.addChild(greenTeaNode)
teaNode.addChild(chaiTeaNode)

sodaNode.addChild(gingerAleNode)
sodaNode.addChild(bitterLemonNode)

tree po一下就能发现是二叉树格式

teaNode.parent
teaNode.parent!.parent

extension TreeNode where T: Equatable {
  func search(_ value: T) -> TreeNode? {
    if value == self.value {
      return self
    }
    for child in children {
      if let found = child.search(value) {
        return found
      }
    }
    return nil
  }
}

tree.search("cocoa")  - 成功
tree.search("chai") - 成功
tree.search("bubbly") - 失败

你可能感兴趣的:(iOS二叉树算法)