Binary tree Level-Order traversal using depth first search (DFS)

Given a binary tree, print out the tree in level order (ie, from left to right, level by level). Output a newline after the end of each level. Breadth First Search (BFS) is not allowed.

     3
   /  \
  9   20
     /  \
    15    7

For example, the level order output of the tree above is:

3
9 20
15 7
C++:
01 bool PrintLevelDFS(Node* head, int level)
02 {
03     if(head==NULL)
04         return false;
05     if(level==1){
06         cout<<head->value<<” “;
07         return true;
08     }
09     bool left,right;
10     left=PrintLevelDFS(head->left,level1);
11     right=PrintLevelDFS(head->right,level1);
12     return left||right;
13 }
14 
15 int main()
16 {
17     for(int i=1;;i++){
18         if(PrintLevelDFS(head,i)==false)
19             break;
20         cout<<endl;
21     }
22 }
Advertisements
This entry was posted in Recursive, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s