Skip to content

Commit 86834a3

Browse files
committed
Time: 173 ms (26.58%), Space: 63.3 MB (24.22%) - LeetHub
1 parent 7228a03 commit 86834a3

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
typedef TreeNode node;
13+
class Solution {
14+
public:
15+
vector<int> arr;
16+
void inorder(node* root) {
17+
if(root == NULL)
18+
return;
19+
inorder(root->left);
20+
arr.push_back(root->val);
21+
inorder(root->right);
22+
}
23+
24+
node* go(int low, int high) {
25+
if(low > high)
26+
return NULL;
27+
28+
int mid = (low + high) / 2;
29+
node* root = new node(arr[mid]);
30+
root->left = go(low, mid - 1);
31+
root->right = go(mid + 1, high);
32+
return root;
33+
}
34+
35+
TreeNode* balanceBST(TreeNode* root) {
36+
inorder(root);
37+
int low = 0, high = arr.size() - 1;
38+
return go(low, high);
39+
}
40+
};

0 commit comments

Comments
 (0)