码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode——Convert Sorted Array to Binary Search Tree

时间:2015-10-01 17:56:49      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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

给一个升序有序的数组,构建一个平衡的二叉查找树。

要平衡就要找中间的数来做头结点,递归构造。

/**
 * 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) {
        
        if(nums.length == 0) {
            return null;
        }
        
        TreeNode root = createBST(nums, 0, nums.length-1);
        
        return root;
    }
    
    public TreeNode createBST(int[] nums, int left, int right) {
        if(left > right) {
            return null;
        }
        int mid = (left + right) / 2;
        TreeNode node = new TreeNode(nums[mid]);
        node.left = createBST(nums, left, mid-1);
        node.right = createBST(nums, mid+1, right);
        
        return node;
    }
}

技术分享

LeetCode——Convert Sorted Array to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/wxisme/p/4851178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!