Balance a Binary Search Tree - LeetCode
Sun May 30 2021 05:32:58 GMT+0000 (Coordinated Universal Time)
Saved by
@Randumkeng
class Solution {
public:
vector<TreeNode*> inorder;
void inorderTraversal(TreeNode* root)
{
if(root==NULL)return ;
inorderTraversal(root->left);
inorder.push_back(root);
inorderTraversal(root->right);
}
TreeNode* build(int l,int r)
{
if(l>r)return NULL;
int mid = l+(r-l)/2;
TreeNode* root = inorder[mid];
root->left = build(l,mid-1);
root->right = build(mid+1,r);
return root;
}
TreeNode* balanceBST(TreeNode* root) {
if(root==NULL)return root;
inorderTraversal(root);
int n = inorder.size();
root = build(0,n-1);
return root;
}
};
content_copyCOPY
Given a binary search tree, return a balanced binary search tree with the same node values.
A binary search tree is balanced if and only if the depth of the two subtrees of every node never differ by more than 1.
If there is more than one answer, return any of them.
https://leetcode.com/problems/balance-a-binary-search-tree/
Comments