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

Leetcode: Convert Sorted Array to Binary Search Tree

时间:2015-04-09 13:51:49      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:二叉排序树   二分法   leetcode   

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

分析:
将已经排序好的数组转成高度平衡的二叉排序树。
依旧二分法。

C++参考代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution
{
private:
    TreeNode *createBST(vector<int> &num, int left, int right)
    {
        if (left > right) return nullptr;
        size_t middle = (left + right) / 2;
        TreeNode *node = new TreeNode(num[middle]);
        node->left = createBST(num, left, middle - 1);
        node->right = createBST(num, middle + 1, right);
        return node;
    }
public:
    TreeNode *sortedArrayToBST(vector<int> &num)
    {
        int size = int(num.size());
        if (size == 0) return nullptr;
        return createBST(num, 0, num.size() - 1);
    }
};

C#参考代码:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution
{
    private TreeNode CreateBST(int[] num, int left, int right)
    {
        if (left > right) return null;
        int middle = (left + right) / 2;
        TreeNode node = new TreeNode(num[middle]);
        node.left = CreateBST(num, left, middle - 1);
        node.right = CreateBST(num, middle + 1, right);
        return node;
    }

    public TreeNode SortedArrayToBST(int[] num)
    {
        if (num.Length == 0) return null;
        return CreateBST(num, 0, num.Length - 1);
    }
}

Leetcode: Convert Sorted Array to Binary Search Tree

标签:二叉排序树   二分法   leetcode   

原文地址:http://blog.csdn.net/theonegis/article/details/44957855

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