Binary Trees in C++ – 4 : Traversal

Question. Print the nodes of a binary tree along with their respective level numbers, in the order specified by preorder traversal.

Solution.

We assume that the root is at level 0. The level number of any other node is 1 greater than the level number of its parent.

We can do the printing of the nodes and their level numbers quite easily using recursion.

——–

struct Node

{

int data;

Node *left;

Node *right;

};

void pre_level (const Node *root, int level)

{

if ( ! root )

return;

cout << root -> data << ”   LEVEL:   ” << level;

pre_level (root->left, level+1);

pre_level (root->right, level+1);

}

———

This code will run in O(n) time on a tree having n nodes.

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

%d bloggers like this: