简体   繁体   English

BST迭代预遍历中的无限循环

[英]Infinite loop in iterative preorder traversal of BST

I am trying to iteratively traverse a BST in preorder, but this function is getting stuck in an infinite loop while printing. 我试图以预定顺序迭代遍历BST,但是此函数在打印时陷入无限循环。 Could someone please tell me why this is 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 and node->left point to random memory locations. 您的循环永远不会结束,因为node->rightnode->left指向随机内存位置。 What is the value of node ? node的值是多少? You haven't assigned anything to it. 您尚未为其分配任何内容。 Its value is random. 它的值是随机的。

Another problem is that you're pushing tree->data onto the stack. 另一个问题是您正在将tree->data推入堆栈。 You actually want to push tree onto the stack. 您实际上想将tree压入堆栈。 Then you can pop a node off the stack and assign it to node . 然后,您可以从堆栈中弹出一个节点并将其分配给node Now you can print node->data and check the children of node . 现在,您可以打印node->data并检查node的子级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM