LeetCode - 108. Convert Sorted Array to Binary Search Tree

链接

108. Convert Sorted Array to Binary Search Tree

题意

将已排序数组转为高度平衡的二叉搜索树

思路

高度平衡即需当任意结点视为根结点时,该树都为二叉搜索树。
因此,可先将中间数作为根结点,根结点的左孩子结点则选取根结点左边区域的中间数,右孩子结点同理。以此类推。

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return f(nums, 0, nums.length - 1);
    }
    
    public TreeNode f(int[] nums, int left, int right) {
        if (left > right) return null;
        int mid = (left + right) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = f(nums, left, mid - 1);
        root.right = f(nums, mid + 1, right);
        return root;
    }
}
posted @ 2017-06-06 10:11  zyoung  阅读(123)  评论(0编辑  收藏  举报