101 Advanced Data Structures using CAll queries, discussions, updates and clarifications regarding Advanced Data Structures using C should be posted here.
tree: Represents the root of the binary search tree.
new: Represents the new node to be inserted.
crr: Represents the current node during traversal.
parent: Represents the parent of the current node.
2. Allocate memory for the new node using malloc() and initialize and ask the user to enter data. Moreover, assign left and right pointers to NULL.
3. If the tree is initially empty, set the new node as the root of the tree.
4. If the tree is not empty, traverse the tree to find the correct position for insertion of newly created Node.
5. To find the correct position, it is required to traverse the tree using pointer crr. This can be done using a loop as discussed below:
Initialization:
crr is initially set to the root node of the tree.
parent is initialized to NULL at the beginning.
Condition:
The loop continues as long as crr is not NULL.
Traversal:
In each iteration of the loop, the value of crr is checked against the value of the new node (new->data).
If the value of the new node is less than the value of the current node (crr->data), it means the new node should be placed in the left subtree. In this case, crr is updated to crr->left.
If the value of the new node is greater than or equal to the value of the current node, it means the new node should be placed in the right subtree. In this case, crr is updated to crr->right.
Parent Update:
Before updating crr, the current node (crr) is assigned to the parent variable.
This is done to keep track of the parent of the current node, which is crucial for linking the new node to the tree.
Loop Continuation or Termination:
The loop continues until crr becomes NULL.
When crr becomes NULL, it indicates that the appropriate position for the new node has been found in the tree, and the loop terminates.
If the value of the new node is less than the value of the last visited node (new->data < parent->data), it means the new node should be inserted as the left child of the last visited node.
In this case, the left pointer of the last visited node (parent->left) is updated to point to the new node (crr).
If the value of the new node is greater than or equal to the value of the last visited node, it means the new node should be inserted as the right child of the last visited node.
In this case, the right pointer of the last visited node (parent->right) is updated to point to the new node (crr).