Method 1: The idea is to do Inorder traversal of given binary tree. While doing Inorder traversal, we pass level of current node also. We keep track of maximum level seen so far and value of deepest node seen so far.
C++
// A C++ program to find value of the deepest node
// in a given binary tree
#include <bits/stdc++.h>
usingnamespacestd;
// A tree node
structNode
{
intdata;
structNode *left, *right;
};
// Utility function to create a new node
Node *newNode(intdata)
{
Node *temp = newNode;
temp->data = data;
temp->left = temp->right = NULL;
returntemp;
}
// maxLevel : keeps track of maximum level seen so far.
// maxLevel : keeps track of maximum level seen so far.
// res : Value of deepest node so far.
// level : Level of root
staticvoidfind(Node root, intlevel)
{
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
staticintdeepestNode(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);
returnres;
}
// Driver code
publicstaticvoidmain(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);
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
classnewNode:
# 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
deffind(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
defdeepestNode(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)
returnres[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
usingSystem;
classGFG
{
// A tree node
publicclassNode
{
publicintdata;
publicNode left, right;
publicNode(intkey)
{
data = key;
left = null;
right = null;
}
}
staticintmaxLevel = -1;
staticintres = -1;
// maxLevel : keeps track of maximum level seen so far.
// res : Value of deepest node so far.
// level : Level of root
staticvoidfind(Node root, intlevel)
{
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
staticintdeepestNode(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);
returnres;
}
// Driver code
publicstaticvoidMain(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);
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
functionfind(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
functiondeepestNode(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);
returnres;
}
// Driver code
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);
document.write(deepestNode(root));
// This code is contributed by rag2127
</script>
Output:
9
Time Complexity: O(n) Method 2 : The idea here is to find the height of the given tree and then print the node at the bottom-most level.
C++
// A C++ program to find value of the
// deepest node in a given binary tree
#include <bits/stdc++.h>
usingnamespacestd;
// A tree node with constructor
classNode
{
public:
intdata;
Node *left, *right;
// constructor
Node(intkey)
{
data = key;
left = NULL;
right = NULL;
}
};
// Utility function to find height
// of a tree, rooted at 'root'.
intheight(Node* root)
{
if(!root) return0;
intleftHt = height(root->left);
intrightHt = height(root->right);
returnmax(leftHt, rightHt) + 1;
}
// levels : current Level
// Utility function to print all
// nodes at a given level.
voiddeepestNode(Node* root, intlevels)
{
if(!root) return;
if(levels == 1)
cout << root->data;
elseif(levels > 1)
{
deepestNode(root->left, levels - 1);
deepestNode(root->right, levels - 1);
}
}
// Driver program
intmain()
{
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);
// Calculating height of tree
intlevels = height(root);
// Printing the deepest node
deepestNode(root, levels);
return0;
}
// This code is contributed by decode2207.
Java
// A Java program to find value of the
// deepest node in a given binary tree
classGFG
{
// A tree node with constructor
staticclassNode
{
intdata;
Node left, right;
// constructor
Node(intkey)
{
data = key;
left = null;
right = null;
}
};
// Utility function to find height
// of a tree, rooted at 'root'.
staticintheight(Node root)
{
if(root == null) return0;
intleftHt = height(root.left);
intrightHt = height(root.right);
returnMath.max(leftHt, rightHt) + 1;
}
// levels : current Level
// Utility function to print all
// nodes at a given level.
staticvoiddeepestNode(Node root,
intlevels)
{
if(root == null) return;
if(levels == 1)
System.out.print(root.data + " ");
elseif(levels > 1)
{
deepestNode(root.left, levels - 1);
deepestNode(root.right, levels - 1);
}
}
// Driver Codede
publicstaticvoidmain(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);
// Calculating height of tree
intlevels = 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
classnew_Node:
def__init__(self, key):
self.data =key
self.left =self.right =None
# Utility function to find height
# of a tree, rooted at 'root'.
defheight(root):
if(notroot):
return0
leftHt =height(root.left)
rightHt =height(root.right)
returnmax(leftHt, rightHt) +1
# levels : current Level
# Utility function to print all
# nodes at a given level.
defdeepestNode(root, levels):
if(notroot):
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
usingSystem;
classGFG
{
// A tree node with constructor
publicclassNode
{
publicintdata;
publicNode left, right;
// constructor
publicNode(intkey)
{
data = key;
left = null;
right = null;
}
};
// Utility function to find height
// of a tree, rooted at 'root'.
staticintheight(Node root)
{
if(root == null) return0;
intleftHt = height(root.left);
intrightHt = height(root.right);
returnMath.Max(leftHt, rightHt) + 1;
}
// levels : current Level
// Utility function to print all
// nodes at a given level.
staticvoiddeepestNode(Node root,
intlevels)
{
if(root == null) return;
if(levels == 1)
Console.Write(root.data + " ");
elseif(levels > 1)
{
deepestNode(root.left, levels - 1);
deepestNode(root.right, levels - 1);
}
}
// Driver Code
publicstaticvoidMain(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);
// Calculating height of tree
intlevels = 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
functionheight(root)
{
if(root == null) return0;
let leftHt = height(root.left);
let rightHt = height(root.right);
returnMath.max(leftHt, rightHt) + 1;
}
// levels : current Level
// Utility function to print all
// nodes at a given level.
functiondeepestNode(root,levels)
{
if(root == null) return;
if(levels == 1)
document.write(root.data + " ");
elseif(levels > 1)
{
deepestNode(root.left, levels - 1);
deepestNode(root.right, levels - 1);
}
}
// Driver Codede
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);
// Calculating height of tree
let levels = height(root);
// Printing the deepest node
deepestNode(root, levels);
// This code is contributed by avanitrachhadiya2155
</script>
Output:
9
Time Complexity: O(n) Thanks to Parth Patekar for suggesting above method.
Method 3: The last node processed from the queue in level order is the deepest node in the binary tree.
C++
// A C++ program to find value of the
// deepest node in a given binary tree
#include <bits/stdc++.h>
usingnamespacestd;
// A tree node with constructor
classNode
{
public:
intdata;
Node *left, *right;
// constructor
Node(intkey)
{
data = key;
left = NULL;
right = NULL;
}
};
// Function to return the deepest node
Node* deepestNode(Node* root)
{
Node* tmp = NULL;
if(root == NULL)
returnNULL;
// 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);
}
returntmp;
}
intmain()
{
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);
Node* deepNode = deepestNode(root);
cout << (deepNode->data);
return0;
}
Java
importjava.util.*;
// A Java program to find value of the
// deepest node in a given binary tree
// A tree node with constructor
publicclassNode
{
intdata;
Node left, right;
// constructor
Node(intkey)
{
data = key;
left = null;
right = null;
}
};
classGfg
{
// Function to return the deepest node
publicstaticNode deepestNode(Node root)
{
Node tmp = null;
if(root == null)
returnnull;
// Creating a Queue
Queue<Node> q = newLinkedList<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);
}
returntmp;
}
publicstaticvoidmain(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);
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
fromcollections importdeque
classnew_Node:
def__init__(self, key):
self.data =key
self.left =self.right =None
defdeepestNode(root):
ifroot ==None:
return0
q =deque()
q.append(root)
node =None
whilelen(q) !=0:
node =q.popleft()
ifnode.left isnotNone:
q.append(node.left)
ifnode.right isnotNone:
q.append(node.right)
returnnode.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
usingSystem;
usingSystem.Collections.Generic;
// A tree node with constructor
publicclassNode
{
public
intdata;
public
Node left, right;
// constructor
public
Node(intkey)
{
data = key;
left = null;
right = null;
}
};
classGfg
{
// Function to return the deepest node
publicstaticNode deepestNode(Node root)
{
Node tmp = null;
if(root == null)
returnnull;
// Creating a Queue
Queue<Node> q = newQueue<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);
}
returntmp;
}
// Driver code
publicstaticvoidMain(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);
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
functiondeepestNode(root)
{
let tmp = null;
if(root == null)
returnnull;
// 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);
}
returntmp;
}
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);
let deepNode = deepestNode(root);
document.write(deepNode.data);
// This code is contributed by unknown2108
</script>
Output
9
Time Complexity: O(n)
Space Complexity: O(n)
?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk
This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy