题目:
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
原文地址:http://blog.csdn.net/theonegis/article/details/44957855