Skip to content

Commit 751789b

Browse files
authored
Create main.cpp
1 parent 75e2dbc commit 751789b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
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+
class Solution {
13+
public:
14+
void inOrder(TreeNode* root, vector<TreeNode*> &inOrderValues){
15+
if(root == NULL) return;
16+
17+
inOrder(root -> left, inOrderValues);
18+
inOrderValues.push_back(root);
19+
inOrder(root -> right, inOrderValues);
20+
}
21+
22+
TreeNode* inorderToBST(int start, int end, vector<TreeNode*> &inOrderValues){
23+
if(start > end) return NULL;
24+
25+
int mid = start + (end - start) / 2;
26+
27+
TreeNode* root = inOrderValues[mid];
28+
29+
root -> left = inorderToBST(start, mid-1, inOrderValues);
30+
root -> right = inorderToBST(mid + 1, end, inOrderValues);
31+
32+
return root;
33+
}
34+
TreeNode* balanceBST(TreeNode* root) {
35+
vector<TreeNode*> inOrderValues;
36+
inOrder(root, inOrderValues);
37+
38+
return inorderToBST(0, inOrderValues.size()-1, inOrderValues);
39+
}
40+
};

0 commit comments

Comments
 (0)