Skip to content

Commit db14400

Browse files
authored
Create 1382. Balance a Binary Search Tree1 (#513)
2 parents 08a3a37 + c89afcd commit db14400

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

1382. Balance a Binary Search Tree1

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public:
3+
vector<int>a;
4+
void inorder(TreeNode*root)
5+
{
6+
if(root)
7+
{
8+
inorder(root->left);
9+
a.push_back(root->val);
10+
inorder(root->right);
11+
}
12+
}
13+
14+
TreeNode* buildTree(int s, int e)
15+
{
16+
if(s > e) return NULL;
17+
int mid = (s+e)/2;
18+
TreeNode* root = new TreeNode(a[mid]);
19+
root->left = buildTree(s, mid-1);
20+
root->right = buildTree(mid+1, e);
21+
return root;
22+
}
23+
24+
TreeNode* balanceBST(TreeNode* root)
25+
{
26+
inorder(root);
27+
return buildTree(0, a.size()-1);
28+
}
29+
};

0 commit comments

Comments
 (0)