Convert Sorted Array to Binary Search Tree

Posted Quest

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Convert Sorted Array to Binary Search Tree相关的知识,希望对你有一定的参考价值。

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

public TreeNode sortedArrayToBST(int[] num) {
    if (num.length == 0) {
        return null;
    }
    TreeNode head = helper(num, 0, num.length - 1);
    return head;
}

public TreeNode helper(int[] num, int low, int high) {
    if (low > high) { 
        return null;
    }
    int mid = (low + high) / 2;
    TreeNode node = new TreeNode(num[mid]);
    node.left = helper(num, low, mid - 1);
    node.right = helper(num, mid + 1, high);
    return node;
}

  

以上是关于Convert Sorted Array to Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

108. Convert Sorted Array to Binary Search Tree

Convert Sorted Array to Binary Search Tree

leetcode 108 Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search [Python]

LC.108.Convert Sorted Array to Binary Search Tree