Created
January 3, 2013 15:09
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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