Normal BST to Balanced BST | Practice | GeeksforGeeks

PHOTO EMBED

Sun Oct 15 2023 11:44:12 GMT+0000 (Coordinated Universal Time)

Saved by @DxBros #bst #balancebst #easy

class Solution{
    
    public:
    // Your are required to complete this function
    // function should return root of the modified BST
    void inorder(Node* root, vector<int>& bst){
        if(!root)
            return;
        inorder(root->left, bst);
        bst.push_back(root->data);
        inorder(root->right, bst);
    }
    
    Node* build(int l , int r, vector<int>& bst){
        if(l > r)
            return nullptr;
        if(l == r)
            return new Node(bst[l]);
        int m = (l + r)/2;
        Node* root = new Node(bst[m]);
        root->left = build(l, m-1,bst);
        root->right = build(m+1,r,bst);
        return root;
    }
    Node* buildBalancedTree(Node* root)
    {
    	// Code here
    	vector<int> bst;
    	inorder(root, bst);
    	return build(0, bst.size() - 1, bst);
    }
};
content_copyCOPY

https://practice.geeksforgeeks.org/problems/normal-bst-to-balanced-bst/1