Binary Trees in C++ – 4 : Traversal
February 15, 2011 Leave a comment
Question. Print the nodes of a binary tree along with their respective level numbers, in the order specified by preorder traversal.
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.
void pre_level (const Node *root, int level)
if ( ! root )
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.