I need a function that takes as an argument pointer to sorted array and returns pointer to a balanced BST. My assumption is that for each node all nodes in left subtree are smaller and all nodes in right subtree are greater or equal than that node. My current attempt ensures a balanced BST but there are duplicates in both left and right subtree of a given node.
What follows is a minimal reproducible example:
#include <iostream>
struct node {
int data;
node* left;
node* right;
node(int d, node* l = nullptr, node* r = nullptr)
: data(d), left(l), right(r)
{}
};
void release(node* root) {
if (!root) return;
release(root->left);
release(root->right);
delete root;
}
node* toTree(const int* sorted_data, int l, int r) {
if (l > r) return nullptr;
size_t m = (l + r) / 2;
node* root = new node(sorted_data[m]);
root->left = toTree(sorted_data, l, m - 1);
root->right = toTree(sorted_data, m + 1, r);
return root;
}
void printInorder(node* root) {
if (!root) return;
printInorder(root->left);
std::cout << root->data << ' ';
printInorder(root->right);
}
int main() {
int arr[9] = { 1, 3, 3, 4, 4, 5, 6, 6, 7 };
node* tree = toTree(arr, 0, 8);
printInorder(tree);
release(tree);
}
If I visualize the BST, it looks like:
4
3 6
1 3 5 6
4 7
According my assumption, the "4" at third level is not in correct subtree.
Balanced is not possible, consider {2, 2, 2, 2, 2}, The only possible tree would be:
2
2
2
2
2
which is not balanced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With