Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save pdu/4444142 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4444142 to your computer and use it in GitHub Desktop.
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. http://leetcode.com/onlinejudge
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *get_bst_(vector<int>::iterator left, vector<int>::iterator right) {
int n = right - left;
if (0 == n) {
return NULL;
}
TreeNode *node = new TreeNode( *(left + n/2) );
node->left = get_bst_(left, left + n/2);
node->right = get_bst_(left + n/2 + 1, right);
return node;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
return get_bst_(num.begin(), num.end());
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment