Construct Binary Search Tree from Array
Given an array of integers, create a Binary Search Tree (BST) from the elements of the array. The output should be the inorder traversal of the constructed BST as a string, with values separated by a space.
[ 15, 10, 20, 8, 12, 16, 25 ]
Explanation. The values are inserted into a BST and then an inorder traversal is performed to get a sorted output.
[ 8, 10, 12 ]
Explanation. Already sorted input yields the same output after inorder traversal of the BST.
[ 12, 8, 10 ]
Explanation. After inserting all elements into the BST and performing an inorder traversal, the elements are in ascending order.
[ 20, 10, 30, 5, 1, 15 ]
Explanation. All integers are added to the BST and an inorder traversal provides the sorted output.
Follow-up: What would be the time complexity of your solution?
The input array will contain at least one element and all elements will be unique. The integers will be in the range of `[-10^5, 10^5]`.
- Views
- 3