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)
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