美文网首页
**Swift 枚举 简单实现 二叉搜索树

**Swift 枚举 简单实现 二叉搜索树

作者: WhiteWhite_iOS | 来源:发表于2016-07-06 23:05 被阅读26次

    练习来自Functional Swift (objc.io)。
    轻微改动。

    //🌲的声明
    indirect enum Tree<T> {
        case Leaf
        case Node( Tree<T>,T,Tree<T> )
    }
    //计算有效数据个数
    func count<T>(tree: Tree<T>) -> Int {
        switch tree {
        case .Leaf:
            return 0
        case let .Node(left, _, right):
            return 1 + count(left) + count(right)
        }
    }
    //空🌲
    func emptySet<T>() -> Tree<T> {
        return Tree.Leaf
    }
    //检测是否为空🌲
    func isEmptySet<T>(tree: Tree<T>) -> Bool {
        switch tree {
        case .Leaf:
            return true
        case .Node(_, _, _):
            return false
        }
    }
    //🌲中所有有效数据集合
    func elements<T>(tree: Tree<T>) -> [T] {
        switch tree {
        case .Leaf:
            return []
        case let .Node(left, x, right):
            return elements(left) + [x] + elements(right)
        }
    }
    //检测是否为2叉搜索🌲
    func isBST<T: Comparable>(tree: Tree<T>) -> Bool {
        switch tree {
        case .Leaf:
            return true
        case let .Node(left, x, right):
            return elements(left).reduce(true){ $1 < x }
                && elements(right).reduce(true){ $1 > x }
                && isBST(left)
                && isBST(right)
        }
    }
    //是否包含.(此方法低效)
    func setContains<T: Comparable>(value: T, tree: Tree<T>) -> Bool {
        switch tree {
        case .Leaf:
            return false
        case let .Node(left, x, right):
            if value == x {
                return true
            }else if value < x {
                return setContains(value, tree: left)
            }else{
                return setContains(value, tree: right)
            }
        }
    }
    //插入
    func setInsert<T: Comparable>(value: T, tree: Tree<T>) -> Tree<T> {
        switch tree {
        case .Leaf:
            return Tree.Node(.Leaf, value, .Leaf)
        case let .Node(left, x, right):
            if value == x {
                return tree
            }else if value < x {
                return Tree.Node(setInsert(value, tree: left), value, right)
            }else{
                return Tree.Node(left, value, setInsert(value, tree: right))
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:**Swift 枚举 简单实现 二叉搜索树

          本文链接:https://www.haomeiwen.com/subject/hookjttx.html