Swift翻转二叉树

252 阅读1分钟

递归法翻转二叉树

///定义二叉树
class Tree {
    var value: String
    var left:Tree?
    var right: Tree?
    init(_ value: String) {
        self.value = value
    }
}

///翻转二叉树
class BinarySolotion {
    func invertBianryTree(_ root: Tree) {
        let temp = root.left
        root.left = root.right
        root.right = temp
        if let leftTree = root.left {
            invertBianryTree(leftTree)
        }
        if let rightTree = root.right {
            invertBianryTree(rightTree)
        }
    }
}