Find the Deepest Node in a Binary Tree
Last Updated :
15 Feb, 2023
Given a binary tree, find the deepest 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 level seen so far and the value of the deepest node seen so far.
Implementation:
C++
// A C++ program to find 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;
}
// maxLevel : keeps track of maximum level seen so far.
// res : Value of deepest node so far.
// level : Level of root
void find(Node *root, int level, int &maxLevel, int &res)
{
if (root != NULL)
{
find(root->left, ++level, maxLevel, res);
// Update level and rescue
if (level > maxLevel)
{
res = root->data;
maxLevel = level;
}
find(root->right, level, maxLevel, res);
}
}
// Returns value of deepest node
int deepestNode(Node *root)
{
// Initialize result and max level
int res = -1;
int maxLevel = -1;
// Updates value "res" and "maxLevel"
// Note that res and maxLen are passed
// by reference.
find(root, 0, maxLevel, res);
return res;
}
// Driver program
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);
cout << deepestNode(root);
return 0;
}
Java
// Java program to find value of the deepest node
// in a given binary tree
class GFG
{
// A tree node
static class Node
{
int data;
Node left, right;
Node(int key)
{
data = key;
left = null;
right = null;
}
}
static int maxLevel = -1;
static int res = -1;
// maxLevel : keeps track of maximum level seen so far.
// res : Value of deepest node so far.
// level : Level of root
static void find(Node root, int level)
{
if (root != null)
{
find(root.left, ++level);
// Update level and rescue
if (level > maxLevel)
{
res = root.data;
maxLevel = level;
}
find(root.right, level);
}
}
// Returns value of deepest node
static int deepestNode(Node root)
{
// Initialize result and max level
/* int res = -1;
int maxLevel = -1; */
// Updates value "res" and "maxLevel"
// Note that res and maxLen are passed
// by reference.
find(root, 0);
return res;
}
// Driver code
public static void main(String[] args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.right = new Node(7);
root.right.right.right = new Node(8);
root.right.left.right.left = new Node(9);
System.out.println(deepestNode(root));
}
}
// This code is contributed by Princi Singh
Python3
"""Python3 program to find value of the
deepest node in a given binary tree"""
# A Binary Tree Node
# Utility function to create a
# new tree node
class newNode:
# Constructor to create a newNode
def __init__(self, data):
self.data= data
self.left = None
self.right = None
self.visited = False
# maxLevel : keeps track of maximum
# level seen so far.
# res : Value of deepest node so far.
# level : Level of root
def find(root, level, maxLevel, res):
if (root != None):
level += 1
find(root.left, level, maxLevel, res)
# Update level and rescue
if (level > maxLevel[0]):
res[0] = root.data
maxLevel[0] = level
find(root.right, level, maxLevel, res)
# Returns value of deepest node
def deepestNode(root) :
# Initialize result and max level
res = [-1]
maxLevel = [-1]
# Updates value "res" and "maxLevel"
# Note that res and maxLen are passed
# by reference.
find(root, 0, maxLevel, res)
return res[0]
# Driver Code
if __name__ == '__main__':
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)
print(deepestNode(root))
# This code is contributed by
# SHUBHAMSINGH10
C#
// C# program to find value of the deepest node
// in a given binary tree
using System;
class GFG
{
// A tree node
public class Node
{
public int data;
public Node left, right;
public Node(int key)
{
data = key;
left = null;
right = null;
}
}
static int maxLevel = -1;
static int res = -1;
// maxLevel : keeps track of maximum level seen so far.
// res : Value of deepest node so far.
// level : Level of root
static void find(Node root, int level)
{
if (root != null)
{
find(root.left, ++level);
// Update level and rescue
if (level > maxLevel)
{
res = root.data;
maxLevel = level;
}
find(root.right, level);
}
}
// Returns value of deepest node
static int deepestNode(Node root)
{
// Initialize result and max level
/* int res = -1;
int maxLevel = -1; */
// Updates value "res" and "maxLevel"
// Note that res and maxLen are passed
// by reference.
find(root, 0);
return res;
}
// Driver code
public static void Main(String[] args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.right = new Node(7);
root.right.right.right = new Node(8);
root.right.left.right.left = new Node(9);
Console.WriteLine(deepestNode(root));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program to find value of the deepest node
// in a given binary tree
class Node
{
constructor(key)
{
this.data = key;
this.left = null;
this.right = null;
}
}
let maxLevel = -1;
let res = -1;
// maxLevel : keeps track of maximum level seen so far.
// res : Value of deepest node so far.
// level : Level of root
function find(root,level)
{
if (root != null)
{
find(root.left, ++level);
// Update level and rescue
if (level > maxLevel)
{
res = root.data;
maxLevel = level;
}
find(root.right, level);
}
}
// Returns value of deepest node
function deepestNode(root)
{
// Initialize result and max level
/* int res = -1;
int maxLevel = -1; */
// Updates value "res" and "maxLevel"
// Note that res and maxLen are passed
// by reference.
find(root, 0);
return res;
}
// Driver code
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.right = new Node(7);
root.right.right.right = new Node(8);
root.right.left.right.left = new Node(9);
document.write(deepestNode(root));
// This code is contributed by rag2127
</script>
Time Complexity: O(n)
Auxiliary Space: O(n) for call stack
Method 2: The idea here is to find the height of the given tree and then print the node at the bottom-most level.
Implementation:
C++
// A C++ program to find value of the
// deepest node in a given binary tree
#include <bits/stdc++.h>
using namespace std;
// A tree node with constructor
class Node
{
public:
int data;
Node *left, *right;
// constructor
Node(int key)
{
data = key;
left = NULL;
right = NULL;
}
};
// Utility function to find height
// of a tree, rooted at 'root'.
int height(Node* root)
{
if(!root) return 0;
int leftHt = height(root->left);
int rightHt = height(root->right);
return max(leftHt, rightHt) + 1;
}
// levels : current Level
// Utility function to print all
// nodes at a given level.
void deepestNode(Node* root, int levels)
{
if(!root) return;
if(levels == 1)
cout << root->data;
else if(levels > 1)
{
deepestNode(root->left, levels - 1);
deepestNode(root->right, levels - 1);
}
}
// Driver program
int main()
{
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->right->left = new Node(5);
root->right->right = new Node(6);
root->right->left->right = new Node(7);
root->right->right->right = new Node(8);
root->right->left->right->left = new Node(9);
// Calculating height of tree
int levels = height(root);
// Printing the deepest node
deepestNode(root, levels);
return 0;
}
// This code is contributed by decode2207.
Java
// A Java program to find value of the
// deepest node in a given binary tree
class GFG
{
// A tree node with constructor
static class Node
{
int data;
Node left, right;
// constructor
Node(int key)
{
data = key;
left = null;
right = null;
}
};
// Utility function to find height
// of a tree, rooted at 'root'.
static int height(Node root)
{
if(root == null) return 0;
int leftHt = height(root.left);
int rightHt = height(root.right);
return Math.max(leftHt, rightHt) + 1;
}
// levels : current Level
// Utility function to print all
// nodes at a given level.
static void deepestNode(Node root,
int levels)
{
if(root == null) return;
if(levels == 1)
System.out.print(root.data + " ");
else if(levels > 1)
{
deepestNode(root.left, levels - 1);
deepestNode(root.right, levels - 1);
}
}
// Driver Codede
public static void main(String args[])
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.right = new Node(7);
root.right.right.right = new Node(8);
root.right.left.right.left = new Node(9);
// Calculating height of tree
int levels = height(root);
// Printing the deepest node
deepestNode(root, levels);
}
}
// This code is contributed by Arnab Kundu
Python3
# A Python3 program to find value of the
# deepest node in a given binary tree
class new_Node:
def __init__(self, key):
self.data = key
self.left = self.right = None
# Utility function to find height
# of a tree, rooted at 'root'.
def height(root):
if(not root):
return 0
leftHt = height(root.left)
rightHt = height(root.right)
return max(leftHt, rightHt) + 1
# levels : current Level
# Utility function to print all
# nodes at a given level.
def deepestNode(root, levels):
if(not root):
return
if(levels == 1):
print(root.data)
elif(levels > 1):
deepestNode(root.left, levels - 1)
deepestNode(root.right, levels - 1)
# Driver Code
if __name__ == '__main__':
root = new_Node(1)
root.left = new_Node(2)
root.right = new_Node(3)
root.left.left = new_Node(4)
root.right.left = new_Node(5)
root.right.right = new_Node(6)
root.right.left.right = new_Node(7)
root.right.right.right = new_Node(8)
root.right.left.right.left = new_Node(9)
# Calculating height of tree
levels = height(root)
# Printing the deepest node
deepestNode(root, levels)
# This code is contributed by PranchalK
C#
// C# program to find value of the
// deepest node in a given binary tree
using System;
class GFG
{
// A tree node with constructor
public class Node
{
public int data;
public Node left, right;
// constructor
public Node(int key)
{
data = key;
left = null;
right = null;
}
};
// Utility function to find height
// of a tree, rooted at 'root'.
static int height(Node root)
{
if(root == null) return 0;
int leftHt = height(root.left);
int rightHt = height(root.right);
return Math.Max(leftHt, rightHt) + 1;
}
// levels : current Level
// Utility function to print all
// nodes at a given level.
static void deepestNode(Node root,
int levels)
{
if(root == null) return;
if(levels == 1)
Console.Write(root.data + " ");
else if(levels > 1)
{
deepestNode(root.left, levels - 1);
deepestNode(root.right, levels - 1);
}
}
// Driver Code
public static void Main(String []args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.right = new Node(7);
root.right.right.right = new Node(8);
root.right.left.right.left = new Node(9);
// Calculating height of tree
int levels = height(root);
// Printing the deepest node
deepestNode(root, levels);
}
}
/* This code contributed by PrinciRaj1992 */
JavaScript
<script>
// A Javascript program to find value of the
// deepest node in a given binary tree
// A tree node with constructor
class Node
{
// constructor
constructor(key)
{
this.data = key;
this.left = null;
this.right = null;
}
}
// Utility function to find height
// of a tree, rooted at 'root
function height(root)
{
if(root == null) return 0;
let leftHt = height(root.left);
let rightHt = height(root.right);
return Math.max(leftHt, rightHt) + 1;
}
// levels : current Level
// Utility function to print all
// nodes at a given level.
function deepestNode(root,levels)
{
if(root == null) return;
if(levels == 1)
document.write(root.data + " ");
else if(levels > 1)
{
deepestNode(root.left, levels - 1);
deepestNode(root.right, levels - 1);
}
}
// Driver Codede
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.right = new Node(7);
root.right.right.right = new Node(8);
root.right.left.right.left = new Node(9);
// Calculating height of tree
let levels = height(root);
// Printing the deepest node
deepestNode(root, levels);
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(n)
Space Complexity : O(n)
Method 3: The last node processed from the queue in level order is the deepest node in the binary tree.
Implementation:
C++
// A C++ program to find value of the
// deepest node in a given binary tree
#include <bits/stdc++.h>
using namespace std;
// A tree node with constructor
class Node
{
public:
int data;
Node *left, *right;
// constructor
Node(int key)
{
data = key;
left = NULL;
right = NULL;
}
};
// Function to return the deepest node
Node* deepestNode(Node* root)
{
Node* tmp = NULL;
if (root == NULL)
return NULL;
// Creating a Queue
queue<Node*> q;
q.push(root);
// Iterates until queue become empty
while (q.size() > 0)
{
tmp = q.front();
q.pop();
if (tmp->left != NULL)
q.push(tmp->left);
if (tmp->right != NULL)
q.push(tmp->right);
}
return tmp;
}
int main()
{
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->right->left = new Node(5);
root->right->right = new Node(6);
root->right->left->right = new Node(7);
root->right->right->right = new Node(8);
root->right->left->right->left = new Node(9);
Node* deepNode = deepestNode(root);
cout << (deepNode->data);
return 0;
}
Java
import java.util.*;
// A Java program to find value of the
// deepest node in a given binary tree
// A tree node with constructor
public class Node
{
int data;
Node left, right;
// constructor
Node(int key)
{
data = key;
left = null;
right = null;
}
};
class Gfg
{
// Function to return the deepest node
public static Node deepestNode(Node root)
{
Node tmp = null;
if (root == null)
return null;
// Creating a Queue
Queue<Node> q = new LinkedList<Node>();
q.offer(root);
// Iterates until queue become empty
while (!q.isEmpty())
{
tmp = q.poll();
if (tmp.left != null)
q.offer(tmp.left);
if (tmp.right != null)
q.offer(tmp.right);
}
return tmp;
}
public static void main(String[] args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.right = new Node(7);
root.right.right.right = new Node(8);
root.right.left.right.left = new Node(9);
Node deepNode = deepestNode(root);
System.out.println(deepNode.data);
}
}
// Code is contributed by mahi_07
Python3
# A Python3 program to find value of the
# deepest node in a given binary tree by method 3
from collections import deque
class new_Node:
def __init__(self, key):
self.data = key
self.left = self.right = None
def deepestNode(root):
if root == None:
return 0
q = deque()
q.append(root)
node = None
while len(q) != 0:
node = q.popleft()
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
return node.data
# Driver Code
if __name__ == '__main__':
root = new_Node(1)
root.left = new_Node(2)
root.right = new_Node(3)
root.left.left = new_Node(4)
root.right.left = new_Node(5)
root.right.right = new_Node(6)
root.right.left.right = new_Node(7)
root.right.right.right = new_Node(8)
root.right.left.right.left = new_Node(9)
# Calculating height of tree
levels = deepestNode(root)
# Printing the deepest node
print(levels)
# This code is contributed by Aprajita Chhawi
C#
// A C# program to find value of the
// deepest node in a given binary tree
using System;
using System.Collections.Generic;
// A tree node with constructor
public class Node
{
public
int data;
public
Node left, right;
// constructor
public
Node(int key)
{
data = key;
left = null;
right = null;
}
};
class Gfg
{
// Function to return the deepest node
public static Node deepestNode(Node root)
{
Node tmp = null;
if (root == null)
return null;
// Creating a Queue
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
// Iterates until queue become empty
while (q.Count != 0)
{
tmp = q.Peek();
q.Dequeue();
if (tmp.left != null)
q.Enqueue(tmp.left);
if (tmp.right != null)
q.Enqueue(tmp.right);
}
return tmp;
}
// Driver code
public static void Main(String[] args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.right = new Node(7);
root.right.right.right = new Node(8);
root.right.left.right.left = new Node(9);
Node deepNode = deepestNode(root);
Console.WriteLine(deepNode.data);
}
}
// This code is contributed by gauravrajput1
JavaScript
<script>
// A Javascript program to find value of the
// deepest node in a given binary tree
// A tree node with constructor
class Node
{
constructor(key)
{
this.data = key;
this.left = null;
this.right = null;
}
}
// Function to return the deepest node
function deepestNode(root)
{
let tmp = null;
if (root == null)
return null;
// Creating a Queue
let q = [];
q.push(root);
// Iterates until queue become empty
while (q.length!=0)
{
tmp = q.shift();
if (tmp.left != null)
q.push(tmp.left);
if (tmp.right != null)
q.push(tmp.right);
}
return tmp;
}
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
root.right.left.right = new Node(7);
root.right.right.right = new Node(8);
root.right.left.right.left = new Node(9);
let deepNode = deepestNode(root);
document.write(deepNode.data);
// This code is contributed by unknown2108
</script>
Time Complexity: O(n)
Auxiliary Space: O(n)
Find the Deepest Node in a Binary Tree
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem