LeetCode-108. Convert Sorted Array to Binary Search Tree(Java)

来源:互联网 发布:如何查看淘宝宝贝类目 编辑:程序博客网 时间:2024/06/06 01:33

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

---------------------------------------------------------------------------------------------------------------------

题意

将按升序排列的数组转换为平衡二叉搜索树

代码

public class Solution {    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) { // Done           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;    }}

阅读全文
0 0