108. Convert Sorted Array to Binary Search Tree

原题链接:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
将一个有序数组转换成一颗平衡树。虽然平衡树的各种操作的实现我看了几天都没写出来,但是这道题只要知道平衡树是什么就可以解答了:

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        TreeNode root = s.sortedArrayToBST(new int[]{1, 3, 5, 7, 9, 11, 13});
        System.out.println(root);
    }

    public TreeNode sortedArrayToBST(int[] nums) {
        return sortedArrayToBSTHelper(nums, 0, nums.length - 1);
    }

    private TreeNode sortedArrayToBSTHelper(int[] nums, int start, int end) {
        while (start <= end) {
            int middle = (start + end) / 2;
            TreeNode node = new TreeNode(nums[middle]);
            node.left = sortedArrayToBSTHelper(nums, start, middle - 1);
            node.right = sortedArrayToBSTHelper(nums, middle + 1, end);
            return node;
        }
        return null;
    }

}
posted @ 2018-03-16 18:32  optor  阅读(102)  评论(0编辑  收藏  举报