what if, the client passes an unsorted array as an argument in construct function, then how it will manage the property of bst . (left should be smaller than the root node and right should be greater than the root node.)
Binary search tree construction
If you pass an unsorted BST. Ideally it will follow the BST property left should be smaller than the root node and right should be greater than the root node.).
But you need to write code for that accordingly.
But we are not checking any condition whether our left node is smaller than the root node or our right node is greater than the root node then how it will work or what is the flow of the code.
private Node construct(int val, Node root) {
if (root == null) {
Node nn = new Node();
nn.data = val;
return nn;
}
if (val < root.data) {
root.left = construct(val, root.left);
}
if (val > root.data) {
root.right = construct(val, root.right);
}
return root;
}
See now in the above approach we will set all elements in the correct position via recursion. Just pass the elements using a for loop in the above method.
This way if the client passes an unsorted array as an argument in construct function, we manage the property of bst