Created
December 8, 2020 01:05
-
-
Save nijiehaha/1cd7765a2f58668f30f72a97cb0aa7e3 to your computer and use it in GitHub Desktop.
Binary tree in swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public indirect enum BinaryTree<T> { | |
case node(BinaryTree<T>, T, BinaryTree<T>) | |
case empty | |
public var count: Int { | |
switch self { | |
case .node(let left, _, let right): | |
return left.count + 1 + right.count | |
case .empty: | |
return 0 | |
} | |
} | |
} | |
extension BinaryTree: CustomStringConvertible { | |
public var description: String { | |
switch self { | |
case .node(let left, let value, let right): | |
return "value: \(value), left = [\(left.description)], right = [\(right.description)]" | |
case .empty: | |
return "" | |
} | |
} | |
} | |
extension BinaryTree: Equatable { | |
public static func == (lhs: BinaryTree<T>, rhs: BinaryTree<T>) -> Bool { | |
switch (lhs, rhs) { | |
case (.empty, .empty): | |
return true | |
default: | |
return false | |
} | |
} | |
} | |
/// 二叉树遍历 | |
extension BinaryTree { | |
public func traverseInOrder(process: (T) -> Void) { | |
if case let .node(left, value, right) = self { | |
left.traverseInOrder(process: process) | |
process(value) | |
right.traverseInOrder(process: process) | |
} | |
} | |
public func traversePreOrder(process: (T) -> Void) { | |
if case let .node(left, value, right) = self { | |
process(value) | |
left.traversePreOrder(process: process) | |
right.traversePreOrder(process: process) | |
} | |
} | |
public func traversePostOrder(process: (T) -> Void) { | |
if case let .node(left, value, right) = self { | |
left.traversePostOrder(process: process) | |
right.traversePostOrder(process: process) | |
process(value) | |
} | |
} | |
/// 用非递归的方法实现二叉树遍历 | |
public func preorderTraversal(process: (T) -> Void) { | |
var node:BinaryTree? | |
var stack = [BinaryTree]() | |
if case .node(_, _, _) = self { | |
node = self | |
while node != .empty || !stack.isEmpty { | |
if case let .node(left, value, _) = node { | |
process(value) | |
stack.append(node!) | |
node = left | |
} else { | |
let right = stack.removeLast() | |
if case let .node(_, _, right) = right { | |
node = right | |
} | |
} | |
} | |
} | |
} | |
} | |
extension BinaryTree { | |
func invert() -> BinaryTree { | |
if case let .node(left, value, right) = self { | |
return .node(right.invert(), value, left.invert()) | |
} else { | |
return .empty | |
} | |
} | |
} | |
/// 参考:https://github.com/raywenderlich/swift-algorithm-club/blob/master/Binary%20Tree/BinaryTree.swift | |
/// 参考:https://www.jianshu.com/p/28f6b0b85ec1 | |
/// 参考:https://medium.com/flawless-app-stories/equatable-for-enum-with-associated-value-e07d9ab20e8e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment