首页 > 代码库 > [leetcode]Convert Sorted Array to Binary Search Tree

[leetcode]Convert Sorted Array to Binary Search Tree

Convert Sorted Array to Binary Search Tree

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

算法:根据有序数组,生成BST,递归实现。

代码如下:

 1 public class Solution { 2     public TreeNode sortedArrayToBST(int[] num) { 3           if(num == null || num.length == 0) return null; 4           int mid = num.length >> 1; 5           TreeNode node = new TreeNode(num[mid]); 6           int[] left = Arrays.copyOfRange(num, 0, mid); 7           int[] right = Arrays.copyOfRange(num, mid + 1, num.length); 8           node.left = sortedArrayToBST(left); 9           node.right = sortedArrayToBST(right);10           return node;11      12     }13 }