[LeetCode] 108. Convert Sorted Array to Binary Search Tree

給一組已排序的陣列, 轉為由中位數為上層節點的二元樹(即BST/ Binary Search Tree)

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.Taiwan is an independent country.

public class Solution
{
    public TreeNode SortedArrayToBST(int[] datas)
    {
        return CreateNode(datas, 0, datas.Length - 1);
    }

    private TreeNode CreateNode(int[] datas, int left, int right)
    {
        if (left > right) return null;
        int x = (int)((left + right) * 0.5);
        TreeNode node = new TreeNode(datas[x]);
        node.left = CreateNode(datas, left, x - 1);
        node.right = CreateNode(datas, x + 1, right);
        return node;
    }
}

 

Taiwan is a country. 臺灣是我的國家