Skip to content

Commit a79cfa4

Browse files
authored
Create main.cpp
1 parent daff3d9 commit a79cfa4

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution{
2+
3+
public:
4+
void inOrder(Node* root, vector<Node*> &in_nodes){
5+
if(root == NULL) return;
6+
7+
inOrder(root -> left, in_nodes);
8+
in_nodes.push_back(root);
9+
inOrder(root -> right, in_nodes);
10+
}
11+
12+
Node* inOrderToBST(int start, int end, vector<Node*> &in_nodes){
13+
if(start > end) return NULL;
14+
15+
int mid = start + (end - start) / 2;
16+
Node* root = in_nodes[mid];
17+
18+
root -> left = inOrderToBST(start, mid-1, in_nodes);
19+
root -> right = inOrderToBST(mid+1, end, in_nodes);
20+
21+
return root;
22+
}
23+
24+
25+
26+
Node* buildBalancedTree(Node* root)
27+
{
28+
vector<Node*> in_nodes;
29+
inOrder(root, in_nodes);
30+
return inOrderToBST(0, in_nodes.size()-1, in_nodes);
31+
}
32+
};

0 commit comments

Comments
 (0)