File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
18 - Binary Search Tree Data Structure Problems/14 - Normal BST to Balanced BST Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments