in the problem section of this question it is said that we have to form a binary search tree from an array and then first we need to print the preorder of it but we can build different bst’s from the array and so preorder can be different,example for
a[ ]={4,3,2,5,6} prerorder can be 4 ,3 ,2, 5, 6 or 4,2,3,5,6.have u in the array given the preorder of the tree because in the sample input given in the description of the question it looks so,if yes then tell me the mistake in my code/approach—link to my code is-------https://ide.codingblocks.com/s/53800.
Otherwise help me with the problem description.
hope u will reply soon.
thanks in advance.
Doubt regarding question---"print bst in the given range"
Hey Nikhil, your code is not printing the preorder of the BST correctly, check for this case
input:
1
10
21 18 2 6 14 24 12 13 3 4
5 10
your code’s output:
# Preorder : 21 18 2 6 14 24
# Nodes within range are : 6
but the expected output is:
# Preorder : 21 18 2 6 3 4 14 12 13 24
# Nodes within range are : 6
And for building BST you can refer the code snippet given below, you can call this function everytime you gets a new node to insert in BST
/* A utility function to insert a new node with given key in BST */
struct node* insert(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(key);
/* Otherwise, recur down the tree */
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
/* return the (unchanged) node pointer */
return node;
}
Hey Nikhil, as you are not responding to this thread, I am marking your doubt as Resolved for now. Re-open it if required.
Please mark your doubts as resolved in your course’s “Ask Doubt” section, when your doubt is resolved.
can you pls tell me how to buildtree from the the given array