Print All Leaf Nodes of a Binary Tree
“Print All Leaf Nodes of a Binary Tree” is a basic problem of tree data structure. Here, we are given a binary tree and our task is to print all leaf nodes of given binary tree from left to right.
Leaf Nodes: Leaf Nodes are those nodes/vertices of a tree, which have no children.
A root node is considered to be a leaf node if there are no children of it.
Here, to print leaf nodes of a binary tree, we will modify the existing recursive preorder traversal algorithm.
The steps required to print all leaf Nodes of a Binary Tree are as follows:
- If root is NULL, then return.
- If root is leaf node, print the data.
- If left or right child exists of root node, then call function for left and right child of the node recursively.
C++ Program to print all leaf nodes of a binary tree is as follows:
/* C++ Program to Print all leaf nodes of a Binary Tree */
#include<bits/stdc++.h>
using namespace std;
typedef struct Node
{
int data;
struct Node *left;
struct Node *right;
Node(int ele)
{
data = ele;
left = NULL;
right = NULL;
}
} Node;
/* Function to Print all leaf nodes of a binary tree */
void printLeafNodes(Node *root)
{
/* If root is empty, return */
if(root == NULL)
return;
/* If root is leaf node, print data */
if(root -> left == NULL && root -> right == NULL)
cout<<root -> data << " ";
/* If there exists left child, recursively call left subtree */
if(root -> left)
printLeafNodes(root -> left);
/* If there exists right child, recursively call right subtree */
if(root -> right)
printLeafNodes(root -> right);
}
int main()
{
/* Creating a Binary tree and inserting some nodes in it */
Node *root = NULL;
root = new Node(1);
root -> left = new Node(2);
root -> right = new Node(3);
root -> left -> left = new Node(4);
root -> left -> right = new Node(5);
root -> right -> left = new Node(6);
root -> right -> right = new Node (7);
root -> left -> right -> left = new Node(8);
root -> right -> left -> right = new Node(9);
/* Calling function to print all leaf nodes of a Binary Tree */
cout<<"The Leaf Nodes of the Tree are ";
printLeafNodes(root);
}
OUTPUT:
The Leaf Nodes of the Tree are 4 8 9 7
Related Posts:
- Binary Tree Traversals
- Count Number of Nodes in a Binary Tree
- Print Alternate Levels of Binary Tree
- Maximum Width of Binary Tree
- Level Order Tree Traversal
- Left View of Binary Tree
- Right View of Binary Tree
- Compute Height of Binary Tree
- Inorder Tree Traversal Using Stack
- Preorder Tree Trasversal Using Stack
- Postorder Tree Traversal Using Stack
- Vertical Order Tree Traversal
- Top View of Binary Tree
- Bottom View of Binary Tree
- Delete Complete Binary Tree
- Check if two trees are mirror Trees of Each Other
- Infix to Postfix Conversion
- Convert Binary Tree to its Mirror Tree
- Check if Binary Tree is Symmetric or Not
- Print All Root to Leaf Paths in a Binary Tree