简体   繁体   English

预购迭代遍历

[英]PreOrder Iterative Traversal

This Iterative Binary tree traversal keeps giving me segmentation fault errors, im not sure how to assign the pointer for the current variable in the tree to the popped element from it since they are 2 different types. 迭代二叉树遍历一直给我分段错误,我不确定如何将树中当前变量的指针分配给从中弹出的元素,因为它们是两种不同的类型。

struct BTnode{
     int data;
     struct BTnode* left;
     struct BTnode* right;
     struct BTnode* parent;
}; 
typedef struct BTnode BTnode_t; 


  typedef struct {
      LL_t* list;
  } stack_t;  //stack is created with a Linked List


void preOrderIter(BTnode_t* root)
{
    stack_t* s = stack_create();
    stack_push(s, root->data); 
    BTnode_t* current;

    while (!stack_is_empty(s))
    {
        current = stack_pop(s);
        printf("%d ", current->data); 

        if ( current->right != NULL)
            stack_push(s, current->right->data);

        if ( current->left != NULL)
            stack_push(s, current->left->data); 
    }

    free(s);
}

Right now you are pushing an integer to stack and then you are trying to pop and assign it to BTNode. 现在,您要推送一个整数以进行堆栈,然后尝试弹出并将其分配给BTNode。 You should push BTNode's to the stack, so when you pop it you can get the data. 您应该将BTNode推送到堆栈中,这样当您将其弹出时就可以获取数据。 I'm guessing it should be like this; 我猜应该是这样。

void preOrderIter(BTnode_t* root)
{
  stack_t* s = stack_create();
  stack_push(s, root); 
  BTnode_t* current;

  while (!stack_is_empty(s))
  {
    current = stack_pop(s);
    printf("%d ", current->data); 

    if ( current->right != NULL)
        stack_push(s, current->right);

    if ( current->left != NULL)
        stack_push(s, current->left); 
  }

  free(s);
}

This is something you need to fix eventually, but I am not sure if this will fix your segmentation fault error. 这是您最终需要解决的问题,但是我不确定这是否可以解决您的细分错误。

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

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