Click here to Skip to main content
15,897,891 members
Articles / Programming Languages / C++
Tip/Trick

Depth First Search (DFS) Non-recursive

Rate me:
Please Sign up or sign in to vote.
3.40/5 (6 votes)
9 Feb 2014CPOL1 min read 50.7K   6   10
DFS algorithm to print the element of a Binary Search Tree in order in which just by traversing with a DFS algorithm is possible

Introduction

A friend asked me about an interview question, how to write a non-recursive DFS algorithm for traversing a binary tree. So I decided to share it with you here.

Background

In the following code, I apply the DFS algorithm to print the element of a Binary Search Tree in order in which just by traversing with a DFS algorithm is possible.

Using the Code

The logic of the algorithm is traverse to left subtrees as much as possible and push them into the stack. When reaching the end, you pop one element from the stack and print it.Then for the node that is popped from the stack again, we should do the same thing (find the left elements) on the right subtree of that node, and we continue until the stack becomes empty.

C++
#include <stack> 
struct BTNode
{

    BTNode(int d)
    {
        data = d;
    }

    int data;
    BTNode* right;
    BTNode* left;
}; 

    void DFS(BTNode* root)
    {
        BTNode* tmp = root;
        std::stack<BTNode*> stck;
        stck.push(tmp);

        //Until the stack is not empty, it means there are nodes to traverse
        while(stck.empty() == false)
        {
            while (tmp->left != 0)
            {
                tmp = tmp->left;
                stck.push(tmp);
            }
            while(stck.empty() == false)
            {
                tmp = stck.top();
                stck.pop();
                std::cout << tmp->data;
                if(tmp->right != 0)
                {
                    tmp = tmp->right;
                    stck.push(tmp);
                    break;
                }
            }
        }

 void CreateTreeExample(BTNode* root)
    {
        BTNode* b1= new BTNode(1);
        BTNode* b2= new BTNode(2);
        BTNode* b3= new BTNode(3);
        BTNode* b4= new BTNode(4);
        BTNode* b5= new BTNode(5);
        BTNode* b6= new BTNode(6);
        BTNode* b7= new BTNode(7);
        BTNode* b8= new BTNode(8);
        BTNode* b9= new BTNode(9);

        b2->left = b1;
        b2->right = b4;
        b6->left = b2;
        b4->left = b3;
        b4->right = b5;
        b7->left = b6;
        b7->right = b8;
        b8->right = b9;
        root = b7;
    } 

To test the algorithm, make a simple binary tree by calling the method:
// 7
// / \
// 6 8
// / \
// 2 9
// / \
// 1 4
// / \
// 3 5

C++
BTNode* root;
CreateTreeExample(root) ;  

and call the DFS method. The output for the example binary tree is:

1
2
3
4
5
6
7
8
9

Points of Interest

FYI, you can use the same concept to solve the question:

Given a binary tree, write a program to convert it to a doubly linked list. The nodes in the doubly linked list are arranged in a sequence formed by a zig-zag level order traversal.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 2 Pin
Andreas Gieriet24-Jan-15 20:42
professionalAndreas Gieriet24-Jan-15 20:42 
QuestionIdiomatic C++ would demand for input iterators (prefix/infix/postfix) Pin
Andreas Gieriet20-Jan-15 14:39
professionalAndreas Gieriet20-Jan-15 14:39 
AnswerRe: Idiomatic C++ would demand for input iterators (prefix/infix/postfix) Pin
Shiva Varshovi_21-Jan-15 15:42
Shiva Varshovi_21-Jan-15 15:42 
GeneralRe: Idiomatic C++ would demand for input iterators (prefix/infix/postfix) Pin
Andreas Gieriet24-Jan-15 20:40
professionalAndreas Gieriet24-Jan-15 20:40 
You talk in the intro of your tip about an interview question and tag it as on C++.

My expectation for the term "traversing": mentioning "iterator", maybe also "visitor pattern", but not a hard coded traversal function.

You are right, you mention that you traverse in-order, but I do not agree that it is a simple modification to your hard coded function to change to pre-order or post-order. Or can you point to the place for pre-order and the place for post-order cout call?

There is no ready-to-use iterator for your own data structure. You implement your hard coded traversal function - why not implement an iterator or a visitor? A very much reduced iterator needs at least a pre-increment operator and a de-reference operator. That operator remembers the current position to be used for the next call, etc. (that's the kind of topics to discuss in an interview if talking about traversing a structure).

For iterative versus recursive: each recursion can be implemented as iteration: in the iteration you have to manage your stack explicitly while in the recursion, you have implicit stack handling but also the danger to screw up with the end criterion.

For executing action (pre-order, in-order, post-order), my preferred algorithm was a visitor: generic for traversing and executing actions at pre-/in-/post-order.
A possible visit function would look like this
C++
struct BTNode;
// abstract visitor interface
class Visitor
{
public:
  typedef std::function<void (BTNode* node)> Action;
public:
  virtual void visit(BTNode* node) = 0;
};
// the tree node including visitor hook
struct BTNode
{
  BTNode(int d): data(d), left(0), right(0) { }
  int data;
  BTNode* right;
  BTNode* left;

  void accept(Visitor& v) { v.visit(this); }
};
// the concrete action visitor
class ActionVisitor: public Visitor
{
private:
  Action _preAction;
  Action _inAction;
  Action _postAction;
public:
  ActionVisitor(Action preAction, Action inAction, Action postAction)
  : _preAction(preAction), _inAction(inAction), _postAction(postAction)
  {}
  virtual void visit(BTNode* node)
  {
    assert(node);
    if (_preAction) _preAction(node);
    if (node->left) node->left->accept(*this);
    if (_inAction) _inAction(node);
    if (node->right) node->right->accept(*this);
    if (_postAction) _postAction(node);
  }
};
...
auto action = [](BTNode* n){std::cout << n->data << std::endl;};
ActionVisitor v(action, 0, 0);
root->accept(v);


In addition: code with variable names "tmp" or alike are a complete no-go. Not being able to give a decent name to a variable is a fail in an interview. Name the current node "current"!

Finally: not properly initializing BTNode is a killer too: left and right are not initialized, all members including data should be initialized in the initializer list.

In my eyes, you give bad advise for answering this interview question.

The person giving this answer in an interview shows that he is

  • not fluent in C++ (constructor issues)
  • not fluent in idiomatic C++ (no mention of iterator - this is a basic concept used in the standard template library)
  • a beginner regarding design patterns (no mention of visitor pattern for traversing structures)


Regards
Andi
GeneralMy vote of 1 Pin
sdcp20-Oct-14 8:35
sdcp20-Oct-14 8:35 
Questionwhile( true) Pin
charlie10027-Jul-14 16:14
charlie10027-Jul-14 16:14 
AnswerRe: while( true) Pin
sdcp20-Oct-14 8:36
sdcp20-Oct-14 8:36 
GeneralRe: while( true) Pin
Shiva Varshovi_20-Jan-15 13:11
Shiva Varshovi_20-Jan-15 13:11 
QuestionNext challenge Pin
YvesDaoust10-Feb-14 0:06
YvesDaoust10-Feb-14 0:06 
AnswerRe: Next challenge Pin
Shiva Varshovi_12-Feb-14 15:11
Shiva Varshovi_12-Feb-14 15:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.