Tuesday, May 5, 2015

Print leaves of binary tree

Problem: Print all the leaves of a binary tree.

Approach: Do inorder traversal and print node's data only if node is a leaf.

Implementation:

void BSTree::printLeaves(Node* node)
{
if(node)
{
printLeaves(node->left);
if(!node->left && !node->right)
std::cout<<node->data<<'\t';
printLeaves(node->right);
}
}

Complexity: O(n)

No comments:

Post a Comment