Given a Binary tree, find out depth of the deepest odd level leaf node. Take root level as depth 1.
Examples:
Input :
Output : 5
Input : 10
/ \
28 13
/ \
14 15
/ \
23 24
Output : 3
We 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 depth of an odd level,if it exists.
Algorithm:
1) return 0 if curr_node == NULL
2) if curr_node is leaf and curr_level is odd,
return curr_level
3) else maximum(depthOdd(left subtree),
depthOdd(right subtree))
Below is the implementation.
// C++ program to find depth of the deepest // odd level node #include<bits/stdc++.h> using namespace std;
// A Tree node struct Node
{ int key;
struct Node *left, *right;
}; // Utility function to create a new node Node* newNode( int key)
{ Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
} // Utility function which // returns whether the current node // is a leaf or not bool isleaf(Node *curr_node)
{ return (curr_node->left == NULL &&
curr_node->right == NULL);
} // function to return the longest // odd level depth if it exists // otherwise 0 int deepestOddLevelDepthUtil(Node *curr_node, int curr_level)
{ // Base case
// return from here
if ( curr_node == NULL)
return 0;
// increment current level
curr_level += 1;
// if curr_level is odd
// and its a leaf node
if ( curr_level % 2 != 0 && isleaf(curr_node))
return curr_level;
return max(deepestOddLevelDepthUtil(curr_node->left,curr_level),
deepestOddLevelDepthUtil(curr_node->right,curr_level));
} // A wrapper over deepestOddLevelDepth() int deepestOddLevelDepth(Node *curr_node)
{ return deepestOddLevelDepthUtil(curr_node, 0);
} // Driver code int main()
{ /* 10
/ \
28 13
/ \
14 15
/ \
23 24
Let us create Binary Tree shown in above example */
Node *root = newNode(10);
root->left = newNode(28);
root->right = newNode(13);
root->right->left = newNode(14);
root->right->right = newNode(15);
root->right->right->left = newNode(23);
root->right->right->right = newNode(24);
cout << deepestOddLevelDepth(root) << endl;
return 0;
} |
// Java program to find depth of the deepest // odd level node class GfG {
// A Tree node static class Node
{ int key;
Node left, right;
} // Utility function to create a new node static Node newNode( int key)
{ Node temp = new Node();
temp.key = key;
temp.left = null ;
temp.right = null ;
return (temp);
} // Utility function which // returns whether the current node // is a leaf or not static boolean isleaf(Node curr_node)
{ return (curr_node.left == null && curr_node.right == null );
} // function to return the longest // odd level depth if it exists // otherwise 0 static int deepestOddLevelDepthUtil(Node curr_node, int curr_level)
{ // Base case
// return from here
if ( curr_node == null )
return 0 ;
// increment current level
curr_level += 1 ;
// if curr_level is odd
// and its a leaf node
if ( curr_level % 2 != 0 && isleaf(curr_node))
return curr_level;
return Math.max(deepestOddLevelDepthUtil(curr_node.left,curr_level),
deepestOddLevelDepthUtil(curr_node.right,curr_level));
} // A wrapper over deepestOddLevelDepth() static int deepestOddLevelDepth(Node curr_node)
{ return deepestOddLevelDepthUtil(curr_node, 0 );
} public static void main(String[] args)
{ /* 10
/ \
28 13
/ \
14 15
/ \
23 24
Let us create Binary Tree shown in above example */
Node root = newNode( 10 );
root.left = newNode( 28 );
root.right = newNode( 13 );
root.right.left = newNode( 14 );
root.right.right = newNode( 15 );
root.right.right.left = newNode( 23 );
root.right.right.right = newNode( 24 );
System.out.println(deepestOddLevelDepth(root));
} } |
# Python3 program to find depth of # the deepest odd level node # 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 which returns # whether the current node is a # leaf or not def isleaf(curr_node) :
return (curr_node.left = = None and
curr_node.right = = None )
# function to return the longest # odd level depth if it exists # otherwise 0 def deepestOddLevelDepthUtil(curr_node,
curr_level) :
# Base case
# return from here
if (curr_node = = None ) :
return 0
# increment current level
curr_level + = 1
# if curr_level is odd and
# its a leaf node
if (curr_level % 2 ! = 0 and
isleaf(curr_node)) :
return curr_level
return max (deepestOddLevelDepthUtil(curr_node.left,
curr_level),
deepestOddLevelDepthUtil(curr_node.right,
curr_level))
# A wrapper over deepestOddLevelDepth() def deepestOddLevelDepth(curr_node) :
return deepestOddLevelDepthUtil(curr_node, 0 )
# Driver Code if __name__ = = '__main__' :
""" 10
/ \
28 13
/ \
14 15
/ \
23 24
Let us create Binary Tree shown in
above example """
root = newNode( 10 )
root.left = newNode( 28 )
root.right = newNode( 13 )
root.right.left = newNode( 14 )
root.right.right = newNode( 15 )
root.right.right.left = newNode( 23 )
root.right.right.right = newNode( 24 )
print (deepestOddLevelDepth(root))
# This code is contributed by # Shubham Singh(SHUBHAMSINGH10) |
// C# program to find depth of the deepest // odd level node using System;
class GfG
{ // A Tree node
class Node
{
public int key;
public Node left, right;
}
// Utility function to create a new node
static Node newNode( int key)
{
Node temp = new Node();
temp.key = key;
temp.left = null ;
temp.right = null ;
return (temp);
}
// Utility function which
// returns whether the current node
// is a leaf or not
static bool isleaf(Node curr_node)
{
return (curr_node.left == null &&
curr_node.right == null );
}
// function to return the longest
// odd level depth if it exists
// otherwise 0
static int deepestOddLevelDepthUtil(Node curr_node,
int curr_level)
{
// Base case
// return from here
if ( curr_node == null )
return 0;
// increment current level
curr_level += 1;
// if curr_level is odd
// and its a leaf node
if ( curr_level % 2 != 0 && isleaf(curr_node))
return curr_level;
return Math.Max(deepestOddLevelDepthUtil(curr_node.left,curr_level),
deepestOddLevelDepthUtil(curr_node.right,curr_level));
}
// A wrapper over deepestOddLevelDepth()
static int deepestOddLevelDepth(Node curr_node)
{
return deepestOddLevelDepthUtil(curr_node, 0);
}
public static void Main(String[] args)
{
/* 10
/ \
28 13
/ \
14 15
/ \
23 24
Let us create Binary Tree shown in above example */
Node root = newNode(10);
root.left = newNode(28);
root.right = newNode(13);
root.right.left = newNode(14);
root.right.right = newNode(15);
root.right.right.left = newNode(23);
root.right.right.right = newNode(24);
Console.WriteLine(deepestOddLevelDepth(root));
}
} // This code is contributed by PrinciRaj1992 |
<script> // JavaScript program to find depth of the deepest // odd level node // A Tree node class Node { constructor()
{
this .key = 0;
this .left = null ;
this .right = null ;
}
} // Utility function to create a new node function newNode(key)
{ var temp = new Node();
temp.key = key;
temp.left = null ;
temp.right = null ;
return (temp);
} // Utility function which // returns whether the current node // is a leaf or not function isleaf(curr_node)
{ return (curr_node.left == null &&
curr_node.right == null );
} // function to return the longest // odd level depth if it exists // otherwise 0 function deepestOddLevelDepthUtil(curr_node, curr_level)
{ // Base case
// return from here
if ( curr_node == null )
return 0;
// increment current level
curr_level += 1;
// if curr_level is odd
// and its a leaf node
if ( curr_level % 2 != 0 && isleaf(curr_node))
return curr_level;
return Math.max(deepestOddLevelDepthUtil(curr_node.left,curr_level),
deepestOddLevelDepthUtil(curr_node.right,curr_level));
} // A wrapper over deepestOddLevelDepth() function deepestOddLevelDepth(curr_node)
{ return deepestOddLevelDepthUtil(curr_node, 0);
} /* 10 / \ 28 13 / \
14 15
/ \
23 24
Let us create Binary Tree shown in above example */ var root = newNode(10);
root.left = newNode(28); root.right = newNode(13); root.right.left = newNode(14); root.right.right = newNode(15); root.right.right.left = newNode(23); root.right.right.right = newNode(24); document.write(deepestOddLevelDepth(root)); </script> |
3
Time complexity: O(h) where h is height of given Binary Tree
Auxiliary space: O(1)
Another Approach(Using Level Order Traversal): Simple and easy to understand
Follow the below steps to solve the above problem:
1) Declare ans variable which will store the depth of the deepest odd level leaf node.
2) Initialize a queue and a level variable with 1 and push the root in the queue.
3) Perform level order traversal and if the frontNode is leaf node and value of level is odd then update value of ans variable from level value and continue traversing.
4) After completion of level Order Traversal the ans variable will the store the depth of deepest odd level leaf node and return it.
Below is the implementation of above approach:
// C++ Program to solve the above problem #include<bits/stdc++.h> using namespace std;
struct Node{
int data;
Node* left;
Node* right;
Node( int item){
data = item;
left = right = NULL;
}
}; Node* newNode( int value){
return new Node(value);
} int deepestOddLevelDepth(Node* root){
int ans = -1;
queue<Node*> q;
q.push(root);
int level = 1;
while (!q.empty()){
int n = q.size();
for ( int i = 0; i<n; i++){
Node* frontNode = q.front();
q.pop();
if (level % 2 != 0 && frontNode->left == NULL && frontNode->right == NULL){
ans = level;
}
if (frontNode->left) q.push(frontNode->left);
if (frontNode->right) q.push(frontNode->right);
}
level++;
}
return ans;
} int main(){
/* 10
/ \
28 13
/ \
14 15
/ \
23 24
Let us create Binary Tree shown in above example */
Node *root = newNode(10);
root->left = newNode(28);
root->right = newNode(13);
root->right->left = newNode(14);
root->right->right = newNode(15);
root->right->right->left = newNode(23);
root->right->right->right = newNode(24);
cout << deepestOddLevelDepth(root) << endl;
return 0;
} // THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002) |
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left;
Node right;
// Constructor to create a new node with the given data
Node( int item) {
data = item;
left = right = null ;
}
} public class Main {
// Create a new node with the given value
static Node newNode( int value) {
return new Node(value);
}
// Function to find the deepest odd-level depth in a binary tree
static int deepestOddLevelDepth(Node root) {
int ans = - 1 ; // Initialize the answer as -1
Queue<Node> q = new LinkedList<>(); // Create a queue for level-order traversal
q.add(root); // Enqueue the root node
int level = 1 ; // Initialize the current level as 1
// Perform level-order traversal
while (!q.isEmpty()) {
int n = q.size(); // Get the number of nodes at the current level
for ( int i = 0 ; i < n; i++) {
Node frontNode = q.poll(); // Dequeue the front node
// Check if the current level is odd and the node is a leaf node
if (level % 2 != 0 && frontNode.left == null && frontNode.right == null ) {
ans = level; // Update the answer with the current level
}
// Enqueue the left and right children if they exist
if (frontNode.left != null ) q.add(frontNode.left);
if (frontNode.right != null ) q.add(frontNode.right);
}
level++; // Move to the next level
}
return ans; // Return the deepest odd-level depth
}
public static void main(String[] args) {
/* 10
/ \
28 13
/ \
14 15
/ \
23 24
Let's create the Binary Tree shown in the above example */
Node root = newNode( 10 );
root.left = newNode( 28 );
root.right = newNode( 13 );
root.right.left = newNode( 14 );
root.right.right = newNode( 15 );
root.right.right.left = newNode( 23 );
root.right.right.right = newNode( 24 );
// Print the deepest odd-level depth
System.out.println(deepestOddLevelDepth(root));
}
} |
from queue import Queue
class Node:
def __init__( self , item):
self .data = item
self .left = None
self .right = None
def newNode(value):
return Node(value)
def deepestOddLevelDepth(root):
ans = - 1
q = Queue()
q.put(root)
level = 1
while not q.empty():
n = q.qsize()
for i in range (n):
frontNode = q.get()
# Check if the current level is odd and the node is a leaf node
if level % 2 ! = 0 and frontNode.left is None and frontNode.right is None :
ans = level
# Enqueue left and right children if they exist
if frontNode.left:
q.put(frontNode.left)
if frontNode.right:
q.put(frontNode.right)
level + = 1
return ans
if __name__ = = "__main__" :
# Constructing the binary tree
# 10
# / \
# 28 13
# / \
# 14 15
# / \
# 23 24
root = newNode( 10 )
root.left = newNode( 28 )
root.right = newNode( 13 )
root.right.left = newNode( 14 )
root.right.right = newNode( 15 )
root.right.right.left = newNode( 23 )
root.right.right.right = newNode( 24 )
# Calculate and print the deepest odd-level depth
print (deepestOddLevelDepth(root))
|
using System;
using System.Collections.Generic;
public class Node
{ public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
} public class DeepestOddLevelDepth
{ // Function to find the depth of the deepest odd-level leaf node
public static int DeepestOddLevel(Node root)
{
int ans = -1; // Variable to store the depth of the deepest odd-level leaf node
Queue<Node> q = new Queue<Node>(); // Queue for level order traversal
q.Enqueue(root); // Enqueue the root node
int level = 1; // Variable to track the level
while (q.Count > 0)
{
int n = q.Count; // Number of nodes at the current level
// Traverse all nodes at the current level
for ( int i = 0; i < n; i++)
{
Node frontNode = q.Dequeue(); // Dequeue the front node
// Check if the current level is odd and the node is a leaf node
if (level % 2 != 0 && frontNode.left == null && frontNode.right == null )
{
ans = level; // Update ans with the current level if conditions met
}
// Enqueue left child if exists
if (frontNode.left != null ) q.Enqueue(frontNode.left);
// Enqueue right child if exists
if (frontNode.right != null ) q.Enqueue(frontNode.right);
}
level++; // Move to the next level
}
return ans; // Return the depth of the deepest odd-level leaf node
}
public static void Main( string [] args)
{
// Creating a binary tree
Node root = new Node(10);
root.left = new Node(28);
root.right = new Node(13);
root.right.left = new Node(14);
root.right.right = new Node(15);
root.right.right.left = new Node(23);
root.right.right.right = new Node(24);
// Finding and printing the depth of the deepest odd-level leaf node
Console.WriteLine( DeepestOddLevel(root));
}
} |
// Node class to represent tree nodes class Node { constructor(item) {
this .data = item;
this .left = null ;
this .right = null ;
}
} // Function to find the depth of the deepest odd-level leaf node in a binary tree function deepestOddLevelDepth(root) {
let ans = -1;
let queue = [root]; // Initialize a queue with the root node
let level = 1; // Initialize the current level as 1
while (queue.length > 0) {
const n = queue.length; // Get the number of nodes at the current level
for (let i = 0; i < n; i++) {
const frontNode = queue.shift(); // Dequeue the front node
// Check if the current level is odd and the node is a leaf node
if (level % 2 !== 0 && frontNode.left === null && frontNode.right === null ) {
ans = level; // Update the answer to the current level
}
// Enqueue the left and right child nodes if they exist
if (frontNode.left) queue.push(frontNode.left);
if (frontNode.right) queue.push(frontNode.right);
}
level++; // Move to the next level
}
return ans; // Return the depth of the deepest odd-level leaf node
} // Helper function to create a new node function newNode(value) {
return new Node(value);
} // Main function to create the binary tree and find the result /*
10
/ \
28 13
/ \
14 15
/ \
23 24
*/
let root = newNode(10); root.left = newNode(28); root.right = newNode(13); root.right.left = newNode(14); root.right.right = newNode(15); root.right.right.left = newNode(23); root.right.right.right = newNode(24); console.log(deepestOddLevelDepth(root)); // Output the result
// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL |
3
Time Complexity: O(N), where N is the number of nodes in given binary tree.
Auxiliary Space: O(N) due to queue data structure.
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.