我是Swift的新手.我试图用递归枚举和泛型实现二叉树:
enum BinaryTree<T> {
indirect case Node(T, BinaryTree<T>, BinaryTree<T>)
case Nothing
}
func inorder<T>(_ root: BinaryTree<T>) -> [T] {
switch root {
case .Nothing:
return []
case let .Node(val, left, right):
return inorder(left) + [val] + inorder(right)
}
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
$ swift ADT.swift
ADT.swift:83:20: error: cannot convert value of type 'BinaryTree<T>' to expected argument type 'BinaryTree<_>'
return inorder(left) + [val] + inorder(right)
^~~~
Run Code Online (Sandbox Code Playgroud)
但是,这有效:
func inorder<T>(_ root: BinaryTree<T>) -> [T] {
switch root {
case .Nothing:
return []
case let …
Run Code Online (Sandbox Code Playgroud)