some algorithmic puzzles, tutorials, interview questions... and stuff...

Friday, September 04, 2009

How to do BFS/BFT and DFS/DFT in a tree

Another one of the classic interview questions is how to do BFT (breadth-first traversal) and DFT (depth-first traversal) in a tree of some kind. For this purpose I'm going to consider a binary tree, just because the algorithm is shorter to write and easier to understand. It can be applied on any kind of tree.
The structure of a tree node should look like this, resembling the node of a linked list:

   1:  struct node {
   2:      int data;
   3:      struct node* left;
   4:      struct node* right;
   5:  };
The recursive solution for DFT is really easy so I'm not going to write it here. For BFT it's a little more complicated, but I want to focus here on the iterative solutions for both, since they also involve two frequently used data structures, a stack and a queue. In the examples below, I use std::queue and std::stack.

For BFT:

   1:  void bfs(node* head) {
   2:      queue<node*> q;
   3:      q.push(head);
   4:      while (!q.empty()) {
   5:          node* n = q.front();
   6:          q.pop();
   7:          cout << n->data << " ";
   8:          if (n->left != 0)
   9:              q.push(n->left);
  10:          if (n->right != 0)
  11:              q.push(n->right);
  12:      }
  13:      cout << endl;
  14:  }

DFT simply exchanges the queue with a stack:

   1:  void dfs(node* head) {
   2:      stack<node*> q;
   3:      q.push(head);
   4:      while (!q.empty()) {
   5:          node* n = q.top();
   6:          q.pop();
   7:          cout << n->data << " ";
   8:          if (n->left != 0)
   9:              q.push(n->left);
  10:          if (n->right != 0)
  11:              q.push(n->right);
  12:      }
  13:      cout << endl;
  14:  }

No comments:

Post a Comment