Follow these steps to create the binary tree:
- Create a node with the following structure: data for storing tree elements, a right pointer to point at the right child of the tree, and a left pointer to point at the left child of the tree.
- Create the root node of the tree. To do this, allocate memory space for a new node and set the root pointer to point at it.
- Prompt the user to enter the tree elements. The value that's entered by the user is assigned to the data member of the root node.
- The left and right pointers of the root node are set to NULL.
- The root node is created. Next, prompt the user to specify the number of elements in the tree.
- Repeat steps 7 to 22 for the number of elements specified by the user.
- Allocate memory space for a new node and set the new pointer so that it points at it.
- Prompt the user to enter the tree element. The tree element that's entered by the user is assigned to the data member of the new node.
- The left and right pointers of the new node are set to NULL.
- To connect the root node to the new node, we need to find a location where it can be connected. To do so, set the temp pointer so that it points at the root node. Compare the values in the data members of the new node and temp node.
- If new ->data > temp->data, go to step 12; otherwise, go to step 16.
- If the right link of temp is NULL—that is, if there is no child on the right of the temp node—then, the new node is added to the right link of the temp node.
- The new node is added as the right child of the temp node. Jump to step 7 to add more tree elements.
- If the right link of the root is not NULL, the temp pointer is set to point where the right pointer of temp is pointing to.
- Go to step 11 for more comparisons.
- If new->data < root->data, go to step 17; otherwise, go to step 21.
- If the left link of the node is NULL—that is, there is no child on the left of the temp node—then the new node is added to the left link.
- The new node is added as the left child of the temp node. Jump to step 7 to add more tree elements.
- If the left link of the root is not NULL, the temp pointer is set to point to where its left pointer is pointing.
- Go to step 11 for more comparisons.
- If new->data = temp->data, this means the value in the new node is a duplicate and cannot be added to the tree.
- Go to step 7 to add more tree elements.
- For inorder traversal, we will follow the algorithm that's provided in the next section. The inorder function is called recursively and the root node of the binary tree is passed to this function.