Skip to content

Instantly share code, notes, and snippets.

@SuryaPratapK
Created June 30, 2023 14:15
Show Gist options
  • Save SuryaPratapK/f99448f0c14e5f0710ae96074fc7c2c9 to your computer and use it in GitHub Desktop.
Save SuryaPratapK/f99448f0c14e5f0710ae96074fc7c2c9 to your computer and use it in GitHub Desktop.
/**
* 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 {
void inTraverse(TreeNode* root,vector<int>& inorder){
if(!root) return;
inTraverse(root->left,inorder);
inorder.push_back(root->val);
inTraverse(root->right,inorder);
}
TreeNode *contructBalancedBST(vector<int>& in,int low,int high){
if(low>high) return NULL;
int mid = low + (high-low)/2;
TreeNode *curr = new TreeNode(in[mid]);
curr->left = contructBalancedBST(in,low,mid-1);
curr->right = contructBalancedBST(in,mid+1,high);
return curr;
}
public:
TreeNode* balanceBST(TreeNode* root) {
if(!root) return NULL;
vector<int> inorder;
inTraverse(root,inorder);
return contructBalancedBST(inorder,0,inorder.size()-1);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment