Display all the leaf nodes from left to right and right to left in a tree

Consider the below image

You need to print the leaf node:

Form left to right: 7, 15, 18, 30

Form right to left : 30, 18, 15, 7

Solution in C++

#include <iostream>
#include <queue>
#include <stack>
using namespace std;

// structure to hold binary tree node
struct Node
{
    int data;
    Node *left, *right;

    Node(int data)
    {
        this->data = data;
        this->left = this->right = nullptr;
    }
};

void print_right_to_left_leaf(Node* node) 
{ 
    if (!node) 
        return; 
  
    if (!node->left && !node->right) 
    { 
        cout << node->data << " "; 
        return; 
    } 
  
    if (node->right) 
        print_right_to_left_leaf(node->right); 
  
    if (node->left) 
        print_right_to_left_leaf(node->left); 
} 

void print_left_to_right_leaf(Node *node) 
{ 
    if (!node) 
        return; 
      
    if (!node->left && !node->right) 
    { 
        cout << node->data << " ";  
        return; 
    } 
  

    if (node->left) 
       print_left_to_right_leaf(node->left); 
          
    if (node->right) 
       print_left_to_right_leaf(node->right); 
} 
 

int main()  
{  
    Node* root = nullptr;
    /* Binary tree:
              16
            /   \
           /     \
          10      25
         /  \    /  \
        /    \  /    \
       7    15 18     30

    */

    root = new Node(16);
    root->left = new Node(10);
    root->right = new Node(25);
    root->left->left = new Node(7);
    root->left->right = new Node(15);
    root->right->left = new Node(18);
    root->right->right = new Node(30);

    cout<<"Printing leaf node from left to right \n";
    print_left_to_right_leaf(root);
    cout<<endl;
    cout<<"Printing leaf node from right to left \n";
    print_right_to_left_leaf(root);
    cout<<endl;

    return 0;  
} 

Output:

Printing leaf node from left to right
7 15 18 30
Printing leaf node from right to left
30 18 15 7

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *