题目:给定一个有序整数数组,元素各不相同且按照升序排列,编写一个算法,创建一个高度最小的二叉查找树.二叉查找树是指对于任意一个结点,左边的结点均小于它,右边的结点均大于它.
核心代码:
<pre><code>` func createMinBST(arr:[Int],start:Int,end:Int) -> TreeNode? {
if arr.count == 0 {
return nil
}
if start < 0 || end < 0 {
return nil
}
if start > end {
return nil
}
let mid:Int = (start + end) / 2
let treeNode:TreeNode = TreeNode()
treeNode.data = "\(arr[mid])"
treeNode.leftChild = createMinBST(arr: arr, start: start, end: mid - 1)
treeNode.rightChild = createMinBST(arr: arr, start: mid + 1, end: end)
return treeNode
}`</code></pre>
测试代码:
<pre><code>var binarySearchTree:BinarySearchTree = BinarySearchTree() var searchData:[Int] = [1,2,3,4,5,6,7] var searchNode:TreeNode? = binarySearchTree.createMinBST(arr: searchData, start: 0, end: searchData.count - 1) tree.treeLevelOrder(root: searchNode) print("FlyElephant")
</code></pre>
网友评论