- 把一個有序的整數數組放到二叉樹中,所構造出來的二叉樹也一定是有序二叉樹。
以中間節點爲根節點將數組分爲左右兩部分,對數組的兩部分用遞歸的方式構建左右子樹。
代碼如下:
class ExampleUnitTest {
/**
定義樹節點
*/
class BiTNode {
var data: Int? = null
var lChild: BiTNode? = null
var rChild: BiTNode? = null
}
/**
* 通過遞歸創建左右節點
*/
private fun arrayToTree(array: Array<Int>, start: Int, end: Int): BiTNode? {
var root: BiTNode? = null
if (end >= start) {
val mid = (start + end + 1) / 2
root = BiTNode()
root.data = array[mid]
root.lChild = arrayToTree(array, start, mid - 1)
root.rChild = arrayToTree(array, mid + 1, end)
}
return root;
}
/**
* 打印樹
*/
private fun printTree(root: BiTNode?) {
if (root == null) {
return
}
if (root.lChild != null) {
printTree(root.lChild)
}
print("${root.data} ")
if (root.rChild != null) {
printTree(root.rChild)
}
}
/**
* 測試
*/
@Test
fun test() {
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
println()
val tree = arrayToTree(array, 0, array.size - 1)
printTree(tree)
}
}
遍歷一次所以時間複雜度
- 如何對二叉樹進行鏡像反轉
通過交換每一個非葉子節點的的左子樹和右子樹。
private fun reverseTree(root: BiTNode?) {
if (root == null){
return
}
reverseTree(root.lChild)
reverseTree(root.rChild)
val tmp = root.lChild
root.lChild = root.rChild;
root.rChild = tmp
}
遍歷一次所以時間複雜度