题解 | #将升序数组转化为平衡二叉搜索树#

将升序数组转化为平衡二叉搜索树

http://www.nowcoder.com/practice/7e5b00f94b254da599a9472fe5ab283d

每次从中间分割数组

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param num int整型一维数组 
     * @return TreeNode类
     */
    public TreeNode sortedArrayToBST(int[] nums) {
        return sortedArrayToBST(nums, 0, nums.length - 1);
    }
    public TreeNode sortedArrayToBST(int[] nums, int left, int right) {
        if (left >= right) {
            return left > right ? null : new TreeNode(nums[left]);
        }
        int mid = left + (right - left) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        TreeNode leftNode = sortedArrayToBST(nums, left, mid - 1);
        TreeNode rightNode = sortedArrayToBST(nums, mid + 1, right);
        root.left = leftNode;
        root.right = rightNode;
        return root;
    }
}
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务