你好,我有这段代码,但是我坚持一步一步地遍历树,例如,我想向左走一步
我可以打印所有树,但是当工作遍历树时,我会卡住
我也可以遍历邮政订单,但我需要一张一张地打印值。
public indirect enum BinaryTree<T> {
case node(BinaryTree<T>, T, BinaryTree<T>)
case empty
public var count: Int {
switch self {
case let .node(left, _, right):
return left.count + 1 + right.count
case .empty:
return 0
}
}
}
extension BinaryTree: CustomStringConvertible {
public var description: String {
switch self {
case let .node(left, value, right):
return "value: \(value), left = [\(left.description)], right = [\(right.description)]"
case .empty:
return ""
}
}
}
let leaf1 = BinaryTree.node(.empty, "Story6", .empty)
let leaf2 = BinaryTree.node(.empty, "Story5", .empty)
let leaf3 = BinaryTree.node(.empty, "Story6", .empty)
let leaf4 = BinaryTree.node(.empty, "Story5", .empty)
let leaf5 = BinaryTree.node(.empty, "Story4", .empty)
let node1 = BinaryTree.node(leaf1, "Story3", leaf2)
let node2 = BinaryTree.node(leaf1, "Story3", leaf2)
let node3 = BinaryTree.node(node2, "Story2", leaf5)
let tree = BinaryTree.node(node1, "Story1", node3)
print(tree)
tree.count // 12
extension BinaryTree {
public func traversePostOrder(process: (T) -> Void) {
if case let .node(left, value, right) = self {
left.traversePostOrder(process: process)
right.traversePostOrder(process: process)
process(value)
}
}
}
tree.traversePostOrder { a in print(a) }
正如我在想逐步遍历树之前写的那样。