(後面是寫在斯威夫特的解決方案,但我希望你能理解並翻譯成喜愛選擇的語言,如果你想使用它)
我們可以很容易地想出一個解決方案,在你的數組數值描述一個完整的(/適當的)二叉樹的特殊情況下,即numElements = 2^(lvl-1)+1
,其中lvl
是你的樹的級別。請參閱下面的功能printFullBinaryTree(...)
。
現在,我們還可以輕鬆地將任何數組擴展爲描述完整二叉樹的數組,參見expandToFullBinary
。 '
通過結合這兩種方法,我們有了任意大小輸入數組的一般方法。
展開任何陣列成一個描述滿二叉樹:
/* given 'arr', returns array expanded to full binary tree (if necessary) */
func expandToFullBinary(arr: [String], expandByCharacter: String = "*") -> [String] {
let binLength = Int(pow(2.0,Double(Int(log2(Double(arr.count)))+1)))-1
if arr.count == binLength {
return arr
}
else {
let diffLength = binLength - arr.count
var arrExpanded = [String](count: binLength, repeatedValue: expandByCharacter)
var j = 0
for i in 0 ..< arr.count {
if i < (arr.count - diffLength) {
arrExpanded[i] = arr[i]
}
else {
arrExpanded[i+j] = arr[i]
j = j+1
}
}
return arrExpanded
}
}
打印陣列(即描述了一個滿二叉樹)爲二叉樹根據你的問題規格:
/* assumes 'arr' describes a full binary tree */
func printFullBinaryTree(arr: [String]) {
var posVectorA : [Int] = [arr.count/2]
var posVectorB : [Int]
var splitSize : Int = arr.count/2
var elemCount = 0
if arr.count < 2 {
print("\(arr.first ?? "")")
}
else {
while elemCount < arr.count {
posVectorB = []
splitSize = splitSize/2
for i in posVectorA {
if elemCount == arr.count {
print("noo")
break
}
print(arr[i], terminator: " ")
elemCount = elemCount + 1
posVectorB.append(i-splitSize-1)
posVectorB.append(i+splitSize+1)
}
print("")
posVectorA = posVectorB
}
}
}
描述完整二叉樹以及描述非滿二叉樹的向量示例:
/* Example */
var arrFullBinary : [String] = ["8", "4", "9", "2", "a", "5", "b", "1", "c", "6", "d", "3", "e", "7", "f"]
var arrNonFullBinary : [String] = ["g", "8", "h", "4", "i", "9", "j", "2", "a", "5", "b", "1", "c", "6", "d", "3", "e", "7", "f"]
printFullBinaryTree(expandToFullBinary(arrFullBinary, expandByCharacter: ""))
/* 1
2 3
4 5 6 7
8 9 a b c d e f */
printFullBinaryTree(expandToFullBinary(arrNonFullBinary, expandByCharacter: ""))
/* 1
2 3
4 5 6 7
8 9 a b c d e f
g h i j */
二進制搜索下降一個路徑,我需要全部擊中它們。 –
我不太確定(我會很高興被糾正),但即使有兩個電話也不會遞歸,總是隻打第一個電話,直到它被用盡。然後轉到堆棧頂部的第二個呼叫。 –