Let's say i need to build this tree from the digits 61207895
and then perform a pre-order traversal of the tree.
6
/ \
/ \
/ \
1 7
/ \ / \
0 2 5 8
\
9
The expected result would be: 6 1 0 2 7 5 8 9
But my code outputs: 6 1 0 2 5 7 8 9
For some reason the position of digits 5
and 7
is switched. Could anyone help me to solve this problem?
This is my main function:
int main()
{
char* digits = malloc(9 * sizeof(char));
printf("Digits:");
scanf("%s", digits);
Node* node = createNode(digits[0] - '0');
for (int i = 1; i < strlen(digits); i++)
{
insertNode(node, digits[i] - '0');
}
free(digits);
printf("Pre-order Traversal: ");
preorderTraversal(node);
return 0;
}
This is my function to insert nodes in the tree:
Node* insertNode(Node* node, int data)
{
if (node != NULL)
{
if (data < node->data)
{
node->left = insertNode(node->left, data);
}
else
{
node->right = insertNode(node->right, data);
}
return node;
}
else
{
return createNode(data);
}
}
And this is my function to perform the Pre-order Traversal:
void preorderTraversal(Node* node)
{
if (node != NULL)
{
printf("%d ", node->data);
preorderTraversal(node->left);
preorderTraversal(node->right);
}
}