[LeetCode] 108. 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
本题要求把有序数组转化成二叉搜索树。二叉搜索树满足性质 左<根<右,对二叉搜索树进行中序遍历将得到有序数组,
因此有序数组的中间值为根结点,前半部分为左子树,后半部分为右子树,各子树均符合该特性。所以使用二分法的方法进行求解。
代码如下:
class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { return arrayToBST(0,nums.size()-1,nums); } TreeNode* arrayToBST(int left,int right,vector<int>& nums){ if(left>right)return NULL; int mid=left+(right-left)/2; TreeNode* root= new TreeNode(nums[mid]); root->left=arrayToBST(left,mid-1,nums); root->right=arrayToBST(mid+1,right,nums); return root; } };