Open In App

Find the Deepest Node in a Binary Tree Using Queue STL – SET 2

Last Updated : 08 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree. The task is to find the value of the deep­est node in the given binary tree.

Examples: 

Input: Root of below tree
            1
          /   \
         2      3
        / \    / \ 
       4   5  6   7
                   \
                    8
Output: 8

Input: Root of below tree
            1
          /   \
         2      3
               / 
              6  
Output: 6

Approach: We have already discussed the two different ways to find the deepest node in a binary tree in this post. Here, we will find the deepest node in the tree using a queue data structure. We will first push the root into the queue and then we will push its child nodes after removing the parent node from the queue. We will continue this process until the queue is empty. The last node in the queue is the deepest node of the binary tree.

Below is the implementation of the above approach as follows: 

C++




// C++ program to find the value of the
// deepest node in a given binary tree.
#include <bits/stdc++.h>
using namespace std;
 
// A tree node
struct Node {
    int data;
    struct Node *left, *right;
};
 
// Utility function to create a new node
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Function to find the deepest node in a tree
int findDeepest(struct Node* root)
{
 
    struct Node* temp = NULL;
 
    queue<Node*> q;
 
    if (root == NULL)
        return 0;
 
    // Push the root node
    q.push(root);
 
    while (!q.empty()) {
 
        temp = q.front();
        q.pop();
 
        // Push left child
        if (temp->left)
            q.push(temp->left);
 
        // Push right child
        if (temp->right)
            q.push(temp->right);
    }
 
    // Return the deepest node's value
    return temp->data;
}
 
// Driver code
int main()
{
    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);
 
    // Function call
    cout << findDeepest(root);
 
    return 0;
}


Java




// Java program to find the value of the
// deepest node in a given binary tree.
import java.util.*;
 
class GFG
{
 
// A tree node
static class Node
{
    int data;
    Node left , right;
};
 
// Utility function to create a new node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}
 
// Function to find the deepest node in a tree
static int findDeepest(Node root)
{
    Node temp = null;
     
    Queue <Node> q = new LinkedList<Node>();
 
    if(root == null)
        return 0;
     
    // Push the root node
    q.add(root);
 
    while(!q.isEmpty())
    {
        temp = q.peek();
        q.remove();
         
        // Push left child
        if(temp.left!=null)
            q.add(temp.left);
         
        // Push right child
        if(temp.right!=null)
            q.add(temp.right);
    }
     
    // Return the deepest node's value
    return temp.data;
}
 
// Driver code
public static void main(String[] args)
{
    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);
     
    // Function call
    System.out.println(findDeepest(root));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to find the value of the
# deepest node in a given binary tree.
from collections import deque
 
# A tree node
class Node:
     
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
 
# Function to find the deepest node in a tree
def findDeepest(root: Node) -> int:
 
    temp = None
    q = deque()
 
    if (root == None):
        return 0
 
    # Push the root node
    q.append(root)
 
    while q:
        temp = q[0]
        q.popleft()
 
        # Push left child
        if (temp.left):
            q.append(temp.left)
 
        # Append right child
        if (temp.right):
            q.append(temp.right)
 
    # Return the deepest node's value
    return temp.data
 
# Driver code
if __name__ == "__main__":
 
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.right.left = Node(5)
    root.right.right = Node(6)
    root.right.left.right = Node(7)
    root.right.right.right = Node(8)
    root.right.left.right.left = Node(9)
 
    # Function call
    print(findDeepest(root))
 
# This code is contributed by sanjeev2552


C#




// C# program to find the value of the
// deepest node in a given binary tree.
using System;
using System.Collections.Generic;
 
class GFG
{
 
// A tree node
public class Node
{
    public int data;
    public Node left , right;
};
 
// Utility function to create a new node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}
 
// Function to find the deepest node in a tree
static int findDeepest(Node root)
{
    Node temp = null;
     
    Queue <Node> q = new Queue <Node>();
 
    if(root == null)
        return 0;
     
    // Push the root node
    q.Enqueue(root);
 
    while(q.Count != 0)
    {
        temp = q.Peek();
        q.Dequeue();
         
        // Push left child
        if(temp.left != null)
            q.Enqueue(temp.left);
         
        // Push right child
        if(temp.right != null)
            q.Enqueue(temp.right);
    }
     
    // Return the deepest node's value
    return temp.data;
}
 
// Driver code
public static void Main(String[] args)
{
    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);
     
    // Function call
    Console.WriteLine(findDeepest(root));
}
}
     
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// Javascript program to find the value of the
// deepest node in a given binary tree.
 
// A tree node
class Node
{
    constructor()
    {
        this.data = 0;
        this.left = null;
        this.right = null;
    }
};
 
// Utility function to create a new node
function newNode(data)
{
    var temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}
 
// Function to find the deepest node in a tree
function findDeepest(root)
{
    var temp = null;
    var q = [];
 
    if (root == null)
        return 0;
     
    // Push the root node
    q.push(root);
 
    while (q.length != 0)
    {
        temp = q[0];
        q.shift();
         
        // Push left child
        if (temp.left != null)
            q.push(temp.left);
         
        // Push right child
        if (temp.right != null)
            q.push(temp.right);
    }
     
    // Return the deepest node's value
    return temp.data;
}
 
// Driver code
var 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);
 
// Function call
document.write(findDeepest(root));
 
// This code is contributed by noob2000
 
</script>


Output

9

Time Complexity: O(N)

Auxiliary Space: O(N) because using queue “q” 



Similar Reads

Find the Deepest Node in a Binary Tree
Given a binary tree, find the deep­est node in it. Examples: Input : Root of below tree 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 Output : 8 Input : Root of below tree 1 / \ 2 3 / 6 Output : 6 Method 1: The idea is to do Inorder traversal of a given binary tree. While doing Inorder traversal, we pass level of current node also. We keep track of the maximum lev
16 min read
Deepest left leaf node in a binary tree
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. 1 / \ 2 3 / / \ 4 5 6 \ \ 7 8 / \ 9 10 The idea is to recursively traverse the given binary tree and while traversing, maintain “level” which will store the current node’s l
13 min read
Deepest left leaf node in a binary tree | iterative approach
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 o
8 min read
Deepest right leaf node in a binary tree | Iterative approach
Given a Binary Tree, find the deepest leaf node that is the right child of its parent. For example, consider the following tree. The deepest right leaf node is the node with the value 10. Examples: Input : 1 / \ 2 3 \ / \ 4 5 6 \ \ 7 8 / \ 9 10 Output : 10 The idea is similar to Method 2 of level order traversal Traverse the tree level by level and
7 min read
Depth of the deepest odd level node in Binary Tree
Given a Binary tree, find out depth of the deepest odd level leaf node. Take root level as depth 1. Examples:  Input : Output : 5Input : 10 / \ 28 13 / \ 14 15 / \ 23 24Output : 3We can traverse the tree starting from the root level and keep curr_level of the node. Increment the curr_level each time we go to left or a right subtree. Return the max
14 min read
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Should we declare as Queue or Priority Queue while using Priority Queue in Java?
Queue: Queue is an Interface that extends the collection Interface in Java and this interface belongs to java.util package. A queue is a type of data structure that follows the FIFO (first-in-first-out ) order. The queue contains ordered elements where insertion and deletion of elements are done at different ends. Priority Queue and Linked List are
3 min read
Lowest Common Ancestor of the deepest leaves of a Binary Tree
Given a Binary Tree consisting of N nodes having distinct values from the range [1, N], the task is to find the lowest common ancestor of the deepest leaves of the binary tree. Examples: Input: Output: 1Explanation: The deepest leaf nodes of the tree are {8, 9, 10}. Lowest common ancestor of these nodes is 1. Input: Output: 6 Approach: The given pr
10 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Find depth of the deepest odd level leaf node
Write a code to get the depth of the deepest odd level leaf node in a binary tree. Consider that level starts with 1. Depth of a leaf node is number of nodes on the path from root to leaf (including both leaf and root).For example, consider the following tree. The deepest odd level node is the node with value 9 and depth of this node is 5. 1 / \ 2
16 min read
Article Tags :
Practice Tags :