1

I was just wondering how I can traverse a binary tree using a while loop (not done recursively).

I have my tree:

typedef struct Node *BSTree;
typedef struct Node {
   int  key;
   BSTree left, right;
} Node;

I just want to know how I can access every single node in a while loop. Could someone show me that? I can't wrap my head around it.

3
  • Section 6.5 of the classic book "The C programming Language" (1988) has an excellent description of binary trees. Commented Oct 16, 2018 at 10:46
  • In my experience, the only reasonable way is to maintain your own stack, analogous to the call stack that would have been kept automatically for you if you used recursion. Commented Oct 16, 2018 at 11:34
  • Depth first or breadth first? Commented Oct 16, 2018 at 14:43

2 Answers 2

3

You need to have a reference to the parent Node.

if root != null store root in current. If current has a left child you set current to left child. If there is no left child and there is a right child store right child in current. If there is no left and right child store parent of current node in in current.

if you take this you will end up in endless loop but if you store the one before the current and compare the relation between the current node and the last node you can traverse the whole tree.

This is not the full answer but it will help.

Sign up to request clarification or add additional context in comments.

1 Comment

Or you can use a stack if you don't want to alter the data structures.
1

You can use a stack for storing the parents that you need to visit when returning from an already visited branch. A way in pseudo-C++ for a preorder traversal:

void (Node * root)
{
  if (root == NULL) 
    return;

  Stack<Node *> stack;
  stack.push(root); 

  Node * p;
  while (not stack.is_empty())
    {
      p = stack.pop();

      // here you visit p 

      if (p->right != NULL)
        stack.push(p->left);

      if (p->left != NULL)
        stack.push(p->right);
    }
}

Note that the left and right branches are pushed in an inverted way, so the first to pop is the left one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.