c - Infinite loop in iterative preorder traversal of BST -
i trying iteratively traverse bst in preorder, function getting stuck in infinite loop while printing. please tell me why happening?
1 typedef struct node_{ 2 int data; 3 struct node_* left; 4 struct node_* right; 5 }bst; 22 void preorder(bst* tree){ 23 if(tree==null){ 24 return; 25 } 26 // create stack 27 stack* stack=create_stack(); 28 // push data onto stack 29 push(stack,tree->data); 30 while(isempty(stack)==0){ 31 struct node_ *node; 32 node->data=top(stack); 33 printf("%d ",node->data); 34 // pop value off stack 35 pop(stack); 36 if(node->right!=null){ 37 //push right child onto stack 38 push(stack,node->right->data); 39 } 40 if(node->left!=null){ 41 // push left child onto stack 42 push(stack,node->left->data); 43 } 44 } 45 }
your loop never ends because node->right
, node->left
point random memory locations. value of node
? haven't assigned it. value random.
another problem you're pushing tree->data
onto stack. want push tree
onto stack. can pop node off stack , assign node
. can print node->data
, check children of node
.
Comments
Post a Comment