我正在浏览Ray Weynderlich的Swift Algo Club文件,他使用此代码获取树高:
func findTreeHeight() -> Int {
if isLeaf {
return 0
} else {
return 1 + max(leftChild?.findTreeHeight() ?? 0, rightChild?.findTreeHeight() ?? 0)
}
}
如果我用这个数组创建树:
let myTree = BinaryTree(arrValues: [7, 2, 5, 10, 9, 1])
高度不应该是4吗?我得到了2。
这是inits和插入函数:
init(value:Int) {
self.value = value
}
convenience init(arrValues:Array<Int>) {
precondition(arrValues.count > 0)
self.init(value: arrValues.first!)
for thisValue in arrValues.dropFirst() {
insertValue(value: thisValue)
}
}
func insertValue(value:Int) {
if value < self.value {
//insert on left
if let leftChild = self.leftChild {
leftChild.insertValue(value: value)
} else {
leftChild = BinaryTree(value: value)
leftChild?.parent = self
}
} else {
//insert on right
if let rightChild = self.rightChild {
rightChild.insertValue(value: value)
} else {
rightChild = BinaryTree(value: value)
rightChild?.parent = self
}
}
}
和伪的扩展打印出来
extension BinaryTree: CustomStringConvertible {
public var description: String {
var s = ""
if let left = leftChild {
s += "(\(left.description)) <- "
}
s += "\(value)"
if let right = rightChild {
s += " -> (\(right.description))"
}
return s
}
}
以下是我关注的链接:
https://github.com/raywenderlich/swift-algorithm-club/tree/master/Binary%20Search%20Tree
答案 0 :(得分:1)
高度为2是正确的。它是从节点到叶节点的最长路径中的边数。