Deepest left leaf node in a binary tree | iterative approach - GeeksforGeeks

31 Mar, 2022
Given a Binary Tree, find the deepest leaf node that is left child of its parent. For example, consider the following tree. The deepest left leaf node is the node with value 9.Examples:  
Input : 
       1
     /   \
    2     3
  /      /  \  
 4      5    6
        \     \
         7     8
        /       \
       9         10


Output : 9
 
Recursive approach to this problem is discussed hereFor iterative approach, idea is similar to Method 2 of level order traversalThe idea is to traverse the tree iteratively and whenever a left tree node is pushed to queue, check if it is leaf node, if it’s leaf node, then update the result. Since we go level by level, the last stored leaf node is deepest one,  
C++
Java
Python3
C#
Javascript
// CPP program to find deepest left leaf// node of binary tree#include <bits/stdc++.h>using namespace std; // tree nodestruct Node {    int data;    Node *left, *right;}; // returns a new tree NodeNode* newNode(int data){    Node* temp = new Node();    temp->data = data;    temp->left = temp->right = NULL;    return temp;} // return the deepest left leaf node// of binary treeNode* getDeepestLeftLeafNode(Node* root){    if (!root)        return NULL;     // create a queue for level order traversal    queue<Node*> q;    q.push(root);     Node* result = NULL;     // traverse until the queue is empty    while (!q.empty()) {        Node* temp = q.front();        q.pop();                   // Since we go level by level, the last        // stored left leaf node is deepest one,        if (temp->left) {            q.push(temp->left);            if (!temp->left->left && !temp->left->right)                result = temp->left;        }                 if (temp->right)            q.push(temp->right);    }    return result;} // driver programint main(){    // construct a tree    Node* root = newNode(1);    root->left = newNode(2);    root->right = newNode(3);    root->left->left = newNode(4);    root->right->left = newNode(5);    root->right->right = newNode(6);    root->right->left->right = newNode(7);    root->right->right->right = newNode(8);    root->right->left->right->left = newNode(9);    root->right->right->right->right = newNode(10);     Node* result = getDeepestLeftLeafNode(root);    if (result)        cout << "Deepest Left Leaf Node :: "             << result->data << endl;    else        cout << "No result, left leaf not found\n";    return 0;}
// Java program to find deepest left leaf// node of binary treeimport java.util.*; class GFG{ // tree nodestatic class Node{    int data;    Node left, right;}; // returns a new tree Nodestatic Node newNode(int data){    Node temp = new Node();    temp.data = data;    temp.left = temp.right = null;    return temp;} // return the deepest left leaf node// of binary treestatic Node getDeepestLeftLeafNode(Node root){    if (root == null)        return null;     // create a queue for level order traversal    Queue<Node> q = new LinkedList<>();    q.add(root);     Node result = null;     // traverse until the queue is empty    while (!q.isEmpty())    {        Node temp = q.peek();        q.remove();         // Since we go level by level, the last        // stored left leaf node is deepest one,        if (temp.left != null)        {            q.add(temp.left);            if (temp.left.left == null &&                temp.left.right == null)                result = temp.left;        }                 if (temp.right != null)            q.add(temp.right);    }    return result;} // Driver Codepublic static void main(String[] args){         // construct a tree    Node root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.right.left = newNode(5);    root.right.right = newNode(6);    root.right.left.right = newNode(7);    root.right.right.right = newNode(8);    root.right.left.right.left = newNode(9);    root.right.right.right.right = newNode(10);     Node result = getDeepestLeftLeafNode(root);    if (result != null)        System.out.println("Deepest Left Leaf Node :: " +                                            result.data);    else        System.out.println("No result, " +                   "left leaf not found");    }} // This code is contributed by Rajput-Ji
# Python3 program to find deepest# left leaf Binary search Tree _MIN = -2147483648_MAX = 2147483648 # Helper function that allocates a new# node with the given data and None# left and right pointers.                                    class newnode:     # Constructor to create a new node    def __init__(self, data):        self.data = data        self.left = None        self.right = None # utility function to return deepest# left leaf nodedef getDeepestLeftLeafNode(root) :     if (not root):        return None     # create a queue for level    # order traversal    q = []    q.append(root)     result = None     # traverse until the queue is empty    while (len(q)):        temp = q[0]        q.pop(0)         if (temp.left):            q.append(temp.left)            if (not temp.left.left and                not temp.left.right):                result = temp.left                 # Since we go level by level,        # the last stored right leaf        # node is deepest one        if (temp.right):            q.append(temp.right)                 return result # Driver Codeif __name__ == '__main__':         # create a binary tree    root = newnode(1)    root.left = newnode(2)    root.right = newnode(3)    root.left.Left = newnode(4)    root.right.left = newnode(5)    root.right.right = newnode(6)    root.right.left.right = newnode(7)    root.right.right.right = newnode(8)    root.right.left.right.left = newnode(9)    root.right.right.right.right = newnode(10)     result = getDeepestLeftLeafNode(root)    if result:        print("Deepest Left Leaf Node ::",                              result.data)    else:        print("No result, Left leaf not found")         # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# program to find deepest left leaf// node of binary treeusing System;using System.Collections.Generic;     class GFG{ // tree nodeclass Node{    public int data;    public Node left, right;}; // returns a new tree Nodestatic Node newNode(int data){    Node temp = new Node();    temp.data = data;    temp.left = temp.right = null;    return temp;} // return the deepest left leaf node// of binary treestatic Node getDeepestLeftLeafNode(Node root){    if (root == null)        return null;     // create a queue for level order traversal    Queue<Node> q = new Queue<Node>();    q.Enqueue(root);     Node result = null;     // traverse until the queue is empty    while (q.Count != 0)    {        Node temp = q.Peek();        q.Dequeue();         // Since we go level by level, the last        // stored left leaf node is deepest one,        if (temp.left != null)        {            q.Enqueue(temp.left);            if (temp.left.left == null &&                temp.left.right == null)                result = temp.left;        }        if (temp.right != null)            q.Enqueue(temp.right);    }    return result;} // Driver Codepublic static void Main(String[] args){         // construct a tree    Node root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.right.left = newNode(5);    root.right.right = newNode(6);    root.right.left.right = newNode(7);    root.right.right.right = newNode(8);    root.right.left.right.left = newNode(9);    root.right.right.right.right = newNode(10);     Node result = getDeepestLeftLeafNode(root);    if (result != null)        Console.WriteLine("Deepest Left Leaf Node :: " +                                           result.data);    else        Console.WriteLine("No result, " +                  "left leaf not found");    }} // This code is contributed by Rajput-Ji
<script>     // JavaScript program to find deepest    // left leaf node of binary tree         class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }         // returns a new tree Node    function newNode(data)    {        let temp = new Node(data);        return temp;    }     // return the deepest left leaf node    // of binary tree    function getDeepestLeftLeafNode(root)    {        if (root == null)            return null;         // create a queue for level order traversal        let q = [];        q.push(root);         let result = null;         // traverse until the queue is empty        while (q.length > 0)        {            let temp = q[0];            q.shift();             // Since we go level by level, the last            // stored left leaf node is deepest one,            if (temp.left != null)            {                q.push(temp.left);                if (temp.left.left == null &&                    temp.left.right == null)                    result = temp.left;            }             if (temp.right != null)                q.push(temp.right);        }        return result;    }         // construct a tree    let root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.right.left = newNode(5);    root.right.right = newNode(6);    root.right.left.right = newNode(7);    root.right.right.right = newNode(8);    root.right.left.right.left = newNode(9);    root.right.right.right.right = newNode(10);       let result = getDeepestLeftLeafNode(root);    if (result != null)        document.write("Deepest Left Leaf Node :: " +                                            result.data);    else        document.write("No result, " +                   "left leaf not found"); </script>
Output:  
Deepest Left Leaf Node :: 9 
YouTubeGeeksforGeeks500K subscribersDeepest left leaf node in a binary tree | Iterative approach | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:15•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=cNBNjZwnPaU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk
SHUBHAMSINGH10
Rajput-Ji
mukesh07
surinderdawra388
cpp-queue
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Min Heap and Max Heap
2-3 Trees | (Search, Insert and Deletion)
Write a program to Calculate Size of a tree | Recursion
Maximum width of a binary tree
Iterative Method to find Height of Binary Tree
Construct a Binary Tree from Postorder and Inorder
Evaluation of Expression Tree
Find the node with minimum value in a Binary Search Tree
Flatten a binary tree into linked list
Maximum Path Sum in a Binary Tree