简体   繁体   中英

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. You should push BTNode's to the stack, so when you pop it you can get the data. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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