22. The algorithm is simple and swift and orderly array into a binary search tree

Creative Commons License Creative Commons

An ordered array in accordance with the ascending order, is converted to a highly balanced binary search tree.

In this problem, a highly balanced binary tree is a binary tree refers to the left and right sub-tree of each node is the height difference between the absolute value of not more than 1.

Example:

Given an ordered array: [-10, -3,0,5,9],

One possible answer is: [0, -3,9, -10, null, 5], it can be expressed below this height balanced binary search tree:

      0
     / \
   -3   9
   /   /
 -10  5

solution:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public var val: Int
 *     public var left: TreeNode?
 *     public var right: TreeNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.left = nil
 *         self.right = nil
 *     }
 * }
 */
class Solution {
    func sortedArrayToBST(_ nums: [Int]) -> TreeNode? {
     if nums.isEmpty {
            return nil
        }
        
        return gBST(nums, 0, nums.count);

    }
    func  gBST(_ nums: [Int], _ l: Int, _ r: Int) -> TreeNode? {
        if (l >= r) {
            return nil;
        }
        let mid = l + (r - l) / 2; 
        
        let node =  TreeNode(nums[mid]);
        node.left = gBST(nums, l, mid);
        node.right = gBST(nums, mid + 1, r);
        
        return node;
    }
}

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/91946799