题目:

108. 将有序数组转换为二叉搜索树

题解:












代码:

/** * code108 */
public class code108 {

    // 左右等分建立左右子树,中间节点作为子树根节点,递归该过程
    public static TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        return sort(nums, 0, nums.length - 1);
    }

    public static TreeNode sort(int nums[], int start, int end) {
        if (start > end) {
            return null;
        }
        int mid = start + (end - start) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = sort(nums, start, mid - 1);
        root.right = sort(nums, mid + 1, end);
        return root;
    }

    public static void main(String[] args) {
        int nums[] = { -10, -3, 0, 5, 9 };
        TreeNode tree = sortedArrayToBST(nums);
        TreeOperation.show(tree);
    }
}

参考:

  1. 将有序数组转换为二叉搜索树
  2. 图解二叉搜索树构造 | 递归 & Python & Go
  3. 分而治之(递归)
  4. 详细通俗的思路分析,多解法
  5. java递归实现