简体   繁体   中英

How to display the next element in sequence for a balanced binary tree? (inorder)

So I'm creating ordered set ADT, using a tree implementation for an assignment. And one of the requirements is implementing an iterator for the set. And I'm having some trouble as to how I'm supposed to return the next element in sequence, when I'm using recursion to traverse the tree. I was thinking of using a while loop to get to the leftmost leaf(node), but I'm not sure how I would get back to the parent node. Here is the tree implementation I am using and its header . Here is the set adt and its header . Any help would be much appreciated.

/*
 * Returns the next element in the sequence represented by the given
 * set iterator.
 */
void *set_next(set_iter_t *iter)
{
  if(iter->node == NULL)
    printf("tree iterator exhausted");
  else
  {
    void *elem;
    while(iter->node->left != NULL)
      iter->node = iter->node->left;
    return elem;
  }
}

Edit: I tried storing the traversal in an array, but it seems like the function isn't properly iterating through the array:

static int i = 0;
void *set_next(set_iter_t *iter)
{

  if(iter->node == NULL)
    printf("tree iterator exhausted");
  else
  {
    int size = iter->node->numitems;
    int arr[size];
    int *p;
    p = arr;
    void *elem;
    store_inorder(iter->node, p, i);
    elem = (p+i);
    return elem;
    ++i;
  }
}

Here is the function I'm using to store the traversal in an array:

void store_inorder(tree_t *tree, int inorder[], int index_ptr)
{
    if (tree == NULL)
        return;
    void *p = malloc(sizeof(intptr_t));;
    p = tree->data;
    /*first recur on left child */
    store_inorder(tree->left, inorder, index_ptr);
    inorder[index_ptr] = (intptr_t)tree->data;
    (index_ptr)++;  // increase index for next entry

    /*now recur on right child */
    store_inorder(tree->right, inorder, index_ptr);
}

You could memorize the location of your iterator by storing the path back from the current location to the root.

Think of Hänsel and Gretel.

Can you simply change the node so that it includes the parent? If iteration is part of the problem definition then having a parent pointer makes the task much easier. And note that you need to go up so long as the child links via its parent's right child, not just the nearest parent.

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