LeetCode108 Convert Sorted Array to Binary Search Tree 有序序列转换为二叉搜索树

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

题源:here;完整实现:here

思路:

通过递归的方式构造二叉树,为了保证树两边的深度相同需要每次先将数列中间的值用来构造结点。代码如下:

TreeNode* sortedArrayToBST(vector<int>& nums) {
	if (nums.size() == 0) return NULL;
	int mid = nums.size() / 2;
	TreeNode *root = new TreeNode(nums[mid]);
	vector<int> leftNums( nums.begin(), nums.begin() + mid );
	vector<int> rightNums(nums.begin() + mid + 1, nums.end());
	root->left = sortedArrayToBST(leftNums);
	root->right = sortedArrayToBST(rightNums);

	return root;
}

 纪念贴图:

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/81101980
今日推荐