I'm new to C++, but I bumped into this problem on HackerRank and ran into a situation that seemed strange to me (coming from R/Python/Java): http://ift.tt/2hTPf2k
To give some background, the HackerRank problem was:
Complete the preOrder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values.
Input Format: Our hidden tester code passes the root node of a binary tree to your preOrder function.
Input:
63 5 2 1 4 6
Expected Output:
3 5 1 4 2 6
I wrote this solution, which I thought would work:
//node is defined as:
/*
struct node
{
int data;
node* left;
node* right;
};
*/
void preOrder(node *root){
while (root != NULL){
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
return;
}
This code, though, never terminates and instead outputs:
3 5 1 1 1 1 1 1 1 1 1... (etc.)
What is strange and I am curious about is that if I change the while loop to the if conditional (as below) the program executes perfectly:
void preOrder(node *root){
if (root == NULL){
return;
}
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
It is my understanding that both if and while ought to assess the condition each time preOrder() is called, but at some point, particularly after the 3rd iteration, the preOrder() function begins to continuously print 1 without terminating.
Any ideas, or could it be related to the main() code which I cannot see?
Aucun commentaire:
Enregistrer un commentaire