美文网首页算法
Swift-创建二叉查找树

Swift-创建二叉查找树

作者: FlyElephant | 来源:发表于2017-05-13 12:19 被阅读8次

    题目:给定一个有序整数数组,元素各不相同且按照升序排列,编写一个算法,创建一个高度最小的二叉查找树.二叉查找树是指对于任意一个结点,左边的结点均小于它,右边的结点均大于它.

    核心代码:
    <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>

    FlyElephant.png

    相关文章

      网友评论

        本文标题:Swift-创建二叉查找树

        本文链接:https://www.haomeiwen.com/subject/xvdxxxtx.html