-
Notifications
You must be signed in to change notification settings - Fork 6
/
BalanceABinaryTree.txt
43 lines (41 loc) · 1.05 KB
/
BalanceABinaryTree.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* balanceBST(TreeNode* root)
{
vector<int> vec;
inorder(vec,root);
return balance(vec,0,vec.size()-1);
}
void inorder(vector<int> &vec,TreeNode* root)
{
if(root==NULL)
return;
inorder(vec,root->left);
vec.push_back(root->val);
inorder(vec,root->right);
return;
}
TreeNode* balance(vector<int> vec,int l,int u)
{
if(l>u)
return NULL;
int mid=l+(u-l)/2;
TreeNode* temp=new TreeNode(vec[mid]);
if(l==u)
return temp;
temp->left=balance(vec,l,mid-1);
temp->right=balance(vec,mid+1,u);
return temp;
}
};