我试图以预定顺序迭代遍历BST,但是此函数在打印时陷入无限循环。有人可以告诉我为什么会这样吗?
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 }
最佳答案
您的循环永远不会结束,因为node->right
和node->left
指向随机的内存位置。 node
的值是什么?您尚未为其分配任何内容。它的值是随机的。
另一个问题是您要将tree->data
压入堆栈。您实际上想将tree
压入堆栈。然后,您可以从堆栈中弹出一个节点并将其分配给node
。现在,您可以打印node->data
并检查node
的子级。
关于c - BST迭代遍历中的无限循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27326790/