Deepest left leaf node in a binary tree
Last Updated :
07 Mar, 2023
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 level in the tree. If current node is left leaf, then check if its level is more than the level of deepest left leaf seen so far. If level is more then update the result. If current node is not leaf, then recursively find maximum depth in left and right subtrees, and return maximum of the two depths.
Implementation:
C++
// A C++ program to find the deepest left leaf in a given binary tree
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int val;
struct Node *left, *right;
};
Node *newNode(int data)
{
Node *temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to find deepest leaf node.
// lvl: level of current node.
// maxlvl: pointer to the deepest left leaf node found so far
// isLeft: A bool indicate that this node is left child of its parent
// resPtr: Pointer to the result
void deepestLeftLeafUtil(Node *root, int lvl, int *maxlvl,
bool isLeft, Node **resPtr)
{
// Base case
if (root == NULL)
return;
// Update result if this node is left leaf and its level is more
// than the maxl level of the current result
if (isLeft && !root->left && !root->right && lvl > *maxlvl)
{
*resPtr = root;
*maxlvl = lvl;
return;
}
// Recur for left and right subtrees
deepestLeftLeafUtil(root->left, lvl+1, maxlvl, true, resPtr);
deepestLeftLeafUtil(root->right, lvl+1, maxlvl, false, resPtr);
}
// A wrapper over deepestLeftLeafUtil().
Node* deepestLeftLeaf(Node *root)
{
int maxlevel = 0;
Node *result = NULL;
deepestLeftLeafUtil(root, 0, &maxlevel, false, &result);
return result;
}
// Driver program to test above function
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);
root->right->right->right->right = newNode(10);
Node *result = deepestLeftLeaf(root);
if (result)
cout << "The deepest left child is " << result->val;
else
cout << "There is no left leaf in the given tree";
return 0;
}
Java
// A Java program to find
// the deepest left leaf
// in a binary tree
// A Binary Tree node
class Node
{
int data;
Node left, right;
// Constructor
public Node(int data)
{
this.data = data;
left = right = null;
}
}
// Class to evaluate pass
// by reference
class Level
{
// maxlevel: gives the
// value of level of
// maximum left leaf
int maxlevel = 0;
}
class BinaryTree
{
Node root;
// Node to store resultant
// node after left traversal
Node result;
// A utility function to
// find deepest leaf node.
// lvl: level of current node.
// isLeft: A bool indicate
// that this node is left child
void deepestLeftLeafUtil(Node node,
int lvl,
Level level,
boolean isLeft)
{
// Base case
if (node == null)
return;
// Update result if this node
// is left leaf and its level
// is more than the maxl level
// of the current result
if (isLeft != false &&
node.left == null &&
node.right == null &&
lvl > level.maxlevel)
{
result = node;
level.maxlevel = lvl;
}
// Recur for left and right subtrees
deepestLeftLeafUtil(node.left, lvl + 1,
level, true);
deepestLeftLeafUtil(node.right, lvl + 1,
level, false);
}
// A wrapper over deepestLeftLeafUtil().
void deepestLeftLeaf(Node node)
{
Level level = new Level();
deepestLeftLeafUtil(node, 0, level, false);
}
// Driver program to test above functions
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.right.left = new Node(5);
tree.root.right.right = new Node(6);
tree.root.right.left.right = new Node(7);
tree.root.right.right.right = new Node(8);
tree.root.right.left.right.left = new Node(9);
tree.root.right.right.right.right = new Node(10);
tree.deepestLeftLeaf(tree.root);
if (tree.result != null)
System.out.println("The deepest left child"+
" is " + tree.result.data);
else
System.out.println("There is no left leaf in"+
" the given tree");
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Python3
# Python program to find the deepest left leaf in a given
# Binary tree
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# A utility function to find deepest leaf node.
# lvl: level of current node.
# maxlvl: pointer to the deepest left leaf node found so far
# isLeft: A bool indicate that this node is left child
# of its parent
# resPtr: Pointer to the result
def deepestLeftLeafUtil(root, lvl, maxlvl, isLeft):
# Base CAse
if root is None:
return
# Update result if this node is left leaf and its
# level is more than the max level of the current result
if(isLeft is True):
if (root.left == None and root.right == None):
if lvl > maxlvl[0] :
deepestLeftLeafUtil.resPtr = root
maxlvl[0] = lvl
return
# Recur for left and right subtrees
deepestLeftLeafUtil(root.left, lvl+1, maxlvl, True)
deepestLeftLeafUtil(root.right, lvl+1, maxlvl, False)
# A wrapper for left and right subtree
def deepestLeftLeaf(root):
maxlvl = [0]
deepestLeftLeafUtil.resPtr = None
deepestLeftLeafUtil(root, 0, maxlvl, False)
return deepestLeftLeafUtil.resPtr
# Driver program to test above function
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)
root.right.right.right.right= Node(10)
result = deepestLeftLeaf(root)
if result is None:
print ("There is not left leaf in the given tree")
else:
print ("The deepst left child is", result.val)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
using System;
// A C# program to find
// the deepest left leaf
// in a binary tree
// A Binary Tree node
public class Node
{
public int data;
public Node left, right;
// Constructor
public Node(int data)
{
this.data = data;
left = right = null;
}
}
// Class to evaluate pass
// by reference
public class Level
{
// maxlevel: gives the
// value of level of
// maximum left leaf
public int maxlevel = 0;
}
public class BinaryTree
{
public Node root;
// Node to store resultant
// node after left traversal
public Node result;
// A utility function to
// find deepest leaf node.
// lvl: level of current node.
// isLeft: A bool indicate
// that this node is left child
public virtual void deepestLeftLeafUtil(Node node, int lvl,
Level level, bool isLeft)
{
// Base case
if (node == null)
{
return;
}
// Update result if this node
// is left leaf and its level
// is more than the maxl level
// of the current result
if (isLeft != false && node.left == null && node.right == null
&& lvl > level.maxlevel)
{
result = node;
level.maxlevel = lvl;
}
// Recur for left and right subtrees
deepestLeftLeafUtil(node.left, lvl + 1, level, true);
deepestLeftLeafUtil(node.right, lvl + 1, level, false);
}
// A wrapper over deepestLeftLeafUtil().
public virtual void deepestLeftLeaf(Node node)
{
Level level = new Level();
deepestLeftLeafUtil(node, 0, level, false);
}
// Driver program to test above functions
public static void Main(string[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.right.left = new Node(5);
tree.root.right.right = new Node(6);
tree.root.right.left.right = new Node(7);
tree.root.right.right.right = new Node(8);
tree.root.right.left.right.left = new Node(9);
tree.root.right.right.right.right = new Node(10);
tree.deepestLeftLeaf(tree.root);
if (tree.result != null)
{
Console.WriteLine("The deepest left child is " + tree.result.data);
}
else
{
Console.WriteLine("There is no left leaf in the given tree");
}
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// A Javascript program to find
// the deepest left leaf
// in a binary tree
class Node
{
constructor(data)
{
this.left = null;
this.right = null;
this.data = data;
}
}
let maxlevel = 0;
let root;
// Node to store resultant
// node after left traversal
let result;
// A utility function to
// find deepest leaf node.
// lvl: level of current node.
// isLeft: A bool indicate
// that this node is left child
function deepestLeftLeafUtil(node, lvl, isLeft)
{
// Base case
if (node == null)
return;
// Update result if this node
// is left leaf and its level
// is more than the maxl level
// of the current result
if (isLeft != false &&
node.left == null &&
node.right == null &&
lvl > maxlevel)
{
result = node;
maxlevel = lvl;
}
// Recur for left and right subtrees
deepestLeftLeafUtil(node.left, lvl + 1, true);
deepestLeftLeafUtil(node.right, lvl + 1, false);
}
// A wrapper over deepestLeftLeafUtil().
function deepestLeftLeaf(node)
{
deepestLeftLeafUtil(node, 0, false);
}
// Driver code
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);
root.right.right.right.right = new Node(10);
deepestLeftLeaf(root);
if (result != null)
document.write("The deepest left child"+
" is " + result.data + "</br>");
else
document.write("There is no left leaf in"+
" the given tree");
// This code is contributed by decode2207
</script>
OutputThe deepest left child is 9
Time Complexity: The function does a simple traversal of the tree, so the complexity is O(n).
Auxiliary Space: O(n) for call stack because using recursion
Iterative Approach(Using Level Order Traversal):
Follow the below steps to solve the above problem:
1) We simply traverse the tree using Level Order Traversal with queue data structure.
2) If current node has left child then we update our answer with left child.
3) Finally return the ans node.
Below is the implementation of above approach:
C++
// Iterative Approach to solve this problem
// C++ code for above approach
// This code is contributed by Yash Agarwal(yashagarwal2852002)
#include<bits/stdc++.h>
using namespace std;
// a binary tree node
struct Node{
int data;
Node* left;
Node* right;
Node(int data){
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
// utility function to create a new tree node
Node* newNode(int data){
return new Node(data);
}
// function will return the deepest left leaf node
Node* deepestLeftLeaf(Node* root){
if(root == NULL) return NULL;
Node* ans = NULL;
queue<Node*> q;
q.push(root);
while(!q.empty()){
Node* front_node = q.front();
q.pop();
if(front_node->left){
q.push(front_node->left);
ans = front_node->left;
}
if(front_node->right){
q.push(front_node->right);
}
}
return ans;
}
// Driver program to test above function
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);
root->right->right->right->right = newNode(10);
Node *result = deepestLeftLeaf(root);
if (result)
cout << "The deepest left child is " << result->data;
else
cout << "There is no left leaf in the given tree";
return 0;
}
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)
Java
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
public class Main {
// utility function create a new node
static Node newNode(int data) {
return new Node(data);
}
// function will return the deepest left leaf node
static Node deepestLeftLeaf(Node root) {
if (root == null) return null;
Node ans = null;
Queue<Node> q = new LinkedList<Node>();
q.add(root);
while (!q.isEmpty()) {
Node front_node = q.poll();
if (front_node.left != null) {
q.add(front_node.left);
ans = front_node.left;
}
if (front_node.right != null) q.add(front_node.right);
}
return ans;
}
// driver code to test above function
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);
root.right.right.right.right = newNode(10);
Node result = deepestLeftLeaf(root);
if (result != null) {
System.out.println("The deepest left child is : " + result.data);
} else {
System.out.println("There is no left leaf in the given tree.");
}
}
}
Python
# Iterative approach to solve this problem
# Python code for the above approach
# a binary tree node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# utility function to create a new tree node
def newNode(data):
return Node(data)
# // function will return the deepest left leaf node
def deepestLeftLeaf(root):
if(root is None):
return
ans = None
q = []
q.append(root)
while(len(q) > 0):
front_node = q.pop(0)
if(front_node.left is not None):
q.append(front_node.left)
ans = front_node.left
if(front_node.right is not None):
q.append(front_node.right)
return ans
# driver program to test above function
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 = deepestLeftLeaf(root)
if(result is not None):
print("The deepest left child is : ")
print(result.data)
else:
print("There is no left leaf in the given tree.")
C#
// C# Program to find sum of all right leaves
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;
}
}
class GFG{
// utility function create a new node
static Node newNode(int data){
return new Node(data);
}
// function will return the deepest left leaf node
static Node deepestLeftLeaf(Node root){
if(root == null) return null;
Node ans = null;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
while(q.Count > 0){
Node front_node = q.Dequeue();
if(front_node.left != null){
q.Enqueue(front_node.left);
ans = front_node.left;
}
if(front_node.right != null) q.Enqueue(front_node.right);
}
return ans;
}
// driver code to test above function
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);
root.right.right.right.right = newNode(10);
Node result = deepestLeftLeaf(root);
if(result != null){
Console.WriteLine("The deepest left child is : " + result.data);
}
else{
Console.WriteLine("There is no left leaf in the given tree.");
}
}
}
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL
JavaScript
// JavaScript implementation of above approach
// a binary tree node
class Node{
constructor(data){
this.data = data;
this.left = null;
this.right = null;
}
}
// utility functionto create a new node
function newNode(data){
return new Node(data);
}
// function will return the deepest left leaf node
function deepestLeftLeaf(root){
if(root == null) return null;
let ans = null;
let q = [];
q.push(root);
while(q.length > 0){
let front_node = q.shift();
if(front_node.left){
q.push(front_node.left);
ans = front_node.left;
}
if(front_node.right) q.push(front_node.right);
}
return ans;
}
// driver code to test above function
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 = deepestLeftLeaf(root);
if(result)
console.log("The deepest left child is : " + result.data);
else
console.log("There is no left leaf in the given tree.");
OutputThe deepest left child is 9
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(N) due to queue data structure.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read