-
- Convert Sorted Array to Binary Search Tree [Tree] [Depth-first Search] [Easy]
- [Tree] [Depth-first Search] [Easy]
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
- Tree
- Depth-first Search
vector<int>& nums
TreeNode*
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if (nums.empty()) return NULL;
return sortedArrayToBST(nums.begin(), nums.end());
}
private:
template<typename Iter>
TreeNode* sortedArrayToBST(Iter first, Iter last) {
auto length = distance(first, last);
if (length <= 0) return NULL;
auto mid = first + length / 2;
TreeNode* root = new TreeNode(*mid);
root->left = sortedArrayToBST(first, mid);
root->right = sortedArrayToBST(mid + 1, last);
return root;
}
};if (nums.empty()) return NULL;
$O(n)$
$O(\log n)$
- Use Divide and Conquer.
-
- Convert Sorted Array to Binary Search Tree [Tree] [Depth-first Search] [Easy]
-
- Convert Sorted List to Binary Search Tree [Linked List] [Depth-first Search] [Medium]