有序数组转换为平衡二叉树(BST)

把有序数组转换为平衡二叉树。

<pre name="code" class="cpp">TreeNode* buildTree(vector<int> &nums,int start,int last)
{
	int mid = (start + last) / 2;
	TreeNode *root = new TreeNode(nums[mid]);
	if(start == last)
	{
		return root;
	}
	if(start <= mid - 1)
	{
		root->left = buildTree(nums,start,mid-1);
	}
	if(mid+1 <=  last)
	{
		root->right = buildTree(nums,mid+1,last);
	}
	return root;
}

TreeNode* sortedArrayToBST(vector<int>& nums) {
	if(nums.empty())
		return NULL;
	return buildTree(nums,0,nums.size()-1);
}

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/yang20141109/article/details/51819584
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞