Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Find maximum (or minimum) in Binary Tree
Next article icon

Get maximum left node in binary tree

Last Updated : 28 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a tree, the task is to find the maximum in an only left node of the binary tree.

Examples:  

Input :             7          /    \         6       5        / \     / \       4  3     2  1         Output : 6  Input :             1          /    \         2       3        /       / \       4       5   6         \    /  \           7  8   9            Output : 8

Traverse with inorder traversal and Apply the condition for the left node only and get maximum of left node. 

Implementation: Let’s try to understand with code. 

C++




// CPP program to print maximum element
// in left node.
#include <bits/stdc++.h>
using namespace std;
 
// A Binary Tree Node
struct Node {
    int data;
    struct Node *left, *right;
};
 
// Get max of left element using
// Inorder traversal
int maxOfLeftElement(Node* root)
{
    int res = INT_MIN;
    if (root == NULL)
        return res;
 
    if (root->left != NULL)
        res = root->left->data;
 
    // Return maximum of three values
    // 1) Recursive max in left subtree
    // 2) Value in left node
    // 3) Recursive max in right subtree
    return max({ maxOfLeftElement(root->left),
                 res,
                 maxOfLeftElement(root->right) });
}
 
// Utility function to create a new tree node
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Driver program to test above functions
int main()
{
    // Let us create binary tree shown in above diagram
    Node* root = newNode(7);
    root->left = newNode(6);
    root->right = newNode(5);
    root->left->left = newNode(4);
    root->left->right = newNode(3);
    root->right->left = newNode(2);
    root->right->right = newNode(1);
 
    /*     7
         /    \
        6       5
       / \     / \
      4  3     2  1          */
    cout << maxOfLeftElement(root);
    return 0;
}
 
 

Java




// Java program to print maximum element
// in left node.
import java.util.*;
class GfG {
 
// A Binary Tree Node
static class Node {
    int data;
    Node left, right;
}
 
// Get max of left element using
// Inorder traversal
static int maxOfLeftElement(Node root)
{
    int res = Integer.MIN_VALUE;
    if (root == null)
        return res;
 
    if (root.left != null)
        res = root.left.data;
 
    // Return maximum of three values
    // 1) Recursive max in left subtree
    // 2) Value in left node
    // 3) Recursive max in right subtree
    return Math.max(maxOfLeftElement(root.left),
       Math.max(res, maxOfLeftElement(root.right)));
}
 
// Utility function to create a new tree node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
// Driver program to test above functions
public static void main(String[] args)
{
    // Let us create binary tree shown in above diagram
    Node root = newNode(7);
    root.left = newNode(6);
    root.right = newNode(5);
    root.left.left = newNode(4);
    root.left.right = newNode(3);
    root.right.left = newNode(2);
    root.right.right = newNode(1);
 
    /* 7
        / \
        6 5
    / \ / \
    4 3 2 1         */
    System.out.println(maxOfLeftElement(root));
}
}
 
 

Python3




# Python program to print maximum element
# in left node.
 
# Utility class to create a
# new tree node
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
     
# Get max of left element using
# Inorder traversal
def maxOfLeftElement(root):
    res = -999999999999
    if (root == None):
        return res
 
    if (root.left != None):
        res = root.left.data
 
    # Return maximum of three values
    # 1) Recursive max in left subtree
    # 2) Value in left node
    # 3) Recursive max in right subtree
    return max({ maxOfLeftElement(root.left), res,
                 maxOfLeftElement(root.right) })
 
# Driver Code
if __name__ == '__main__':
 
    # Let us create binary tree shown
    # in above diagram
    root = newNode(7)
    root.left = newNode(6)
    root.right = newNode(5)
    root.left.left = newNode(4)
    root.left.right = newNode(3)
    root.right.left = newNode(2)
    root.right.right = newNode(1)
 
    #     7
    #     / \
    # 6     5
    # / \     / \
    # 4 3     2 1        
    print(maxOfLeftElement(root))
 
# This code is contributed by PranchalK
 
 

C#




// C# program to print maximum element
// in left node.
using System;
 
class GfG
{
 
    // A Binary Tree Node
    class Node
    {
        public int data;
        public Node left, right;
    }
 
    // Get max of left element using
    // Inorder traversal
    static int maxOfLeftElement(Node root)
    {
        int res = int.MinValue;
        if (root == null)
            return res;
 
        if (root.left != null)
            res = root.left.data;
 
        // Return maximum of three values
        // 1) Recursive max in left subtree
        // 2) Value in left node
        // 3) Recursive max in right subtree
        return Math.Max(maxOfLeftElement(root.left),
        Math.Max(res, maxOfLeftElement(root.right)));
    }
 
    // Utility function to create a new tree node
    static Node newNode(int data)
    {
        Node temp = new Node();
        temp.data = data;
        temp.left = null;
        temp.right = null;
        return temp;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        // Let us create binary tree
        // shown in above diagram
        Node root = newNode(7);
        root.left = newNode(6);
        root.right = newNode(5);
        root.left.left = newNode(4);
        root.left.right = newNode(3);
        root.right.left = newNode(2);
        root.right.right = newNode(1);
 
        /* 7
            / \
            6 5
        / \ / \
        4 3 2 1         */
        Console.WriteLine(maxOfLeftElement(root));
    }
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
// JavaScript program to print maximum element
// in left node.
// A Binary Tree Node
class Node
{
  constructor()
  {
    this.data = 0;
    this.left = null;
    this.right = null;
  }
}
// Get max of left element using
// Inorder traversal
function maxOfLeftElement(root)
{
    var res = -1000000000;
    if (root == null)
        return res;
    if (root.left != null)
        res = root.left.data;
    // Return maximum of three values
    // 1) Recursive max in left subtree
    // 2) Value in left node
    // 3) Recursive max in right subtree
    return Math.max(maxOfLeftElement(root.left),
    Math.max(res, maxOfLeftElement(root.right)));
}
// Utility function to create a new tree node
function newNode(data)
{
    var temp = new Node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
// Driver code
// Let us create binary tree
// shown in above diagram
var root = newNode(7);
root.left = newNode(6);
root.right = newNode(5);
root.left.left = newNode(4);
root.left.right = newNode(3);
root.right.left = newNode(2);
root.right.right = newNode(1);
/* 7
    / \
    6 5
/ \ / \
4 3 2 1         */
document.write(maxOfLeftElement(root));
 
</script>
 
 
Output
6

Iterative Approach(using queue):
Follow the below steps to solve the given problem:
1). Perform level order traversal using queue data structure.
2). At each node check it’s left children is null or not. If the left children is not null then compare its with the existing max left value.
3). If the current node left child value is greater than the existing value then update the max left value with current node left child value.

Below is the implementation of above approach:

C++




// C++ Program to print maximum element
// in left node
#include<bits/stdc++.h>
using namespace std;
 
// a binary tree node
struct Node{
    int data;
    Node* left;
    Node* right;
};
 
// utiltity function to create a new tree node
Node* newNode(int data){
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// get max of left element by
// level order traversal using queue
int maxOfLeftElement(Node* root){
    int res = INT_MIN;
    if(root == NULL) return res;
    queue<Node*> q;
    q.push(root);
    while(!q.empty()){
        Node* front_node = q.front();
        q.pop();
        if(front_node->left != NULL){
            res = max(res, front_node->left->data);
        }
        if(front_node->left) q.push(front_node->left);
        if(front_node->right) q.push(front_node->right);
    }
    return res;
}
 
// Driver program to test above functions
int main(){
    // Let us create binary tree shown in above diagram
    Node* root = newNode(7);
    root->left = newNode(6);
    root->right = newNode(5);
    root->left->left = newNode(4);
    root->left->right = newNode(3);
    root->right->left = newNode(2);
    root->right->right = newNode(1);
  
    /*     7
         /    \
        6       5
       / \     / \
      4  3     2  1          */
    cout << maxOfLeftElement(root);
    return 0;
}
 
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)
 
 

Java




// Java program for the above approach
import java.util.*;
 
// a binary tree node
class Node {
    int data;
    Node left;
    Node right;
 
    Node(int data) {
        this.data = data;
        left = right = null;
    }
}
 
class Main {
 
    // get max of left element by
    // level order traversal using queue
    static int maxOfLeftElement(Node root) {
        int res = Integer.MIN_VALUE;
        if(root == null) return res;
        Queue<Node> q = new LinkedList<Node>();
        q.offer(root);
        while(!q.isEmpty()){
            Node front_node = q.poll();
            if(front_node.left != null){
                res = Math.max(res, front_node.left.data);
            }
            if(front_node.left != null) q.offer(front_node.left);
            if(front_node.right != null) q.offer(front_node.right);
        }
        return res;
    }
 
    // Driver program to test above functions
    public static void main(String[] args) {
        // Let us create binary tree shown in above diagram
        Node root = new Node(7);
        root.left = new Node(6);
        root.right = new Node(5);
        root.left.left = new Node(4);
        root.left.right = new Node(3);
        root.right.left = new Node(2);
        root.right.right = new Node(1);
 
        /*     7
             /    \
            6       5
           / \     / \
          4  3     2  1          */
        System.out.println(maxOfLeftElement(root));
    }
}
 
// This code is contributed by codebraxnzt
 
 

Python3




from queue import Queue
 
# a binary tree node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# get max of left element by level order traversal using queue
def maxOfLeftElement(root):
    res = float('-inf')
    if root is None:
        return res
    q = Queue()
    q.put(root)
    while not q.empty():
        front_node = q.get()
        if front_node.left:
            res = max(res, front_node.left.data)
        if front_node.left:
            q.put(front_node.left)
        if front_node.right:
            q.put(front_node.right)
    return res
 
# Driver program to test above functions
if __name__ == '__main__':
    # Let us create binary tree shown in above diagram
    root = Node(7)
    root.left = Node(6)
    root.right = Node(5)
    root.left.left = Node(4)
    root.left.right = Node(3)
    root.right.left = Node(2)
    root.right.right = Node(1)
 
    """
         7
        / \
       6   5
      / \ / \
     4  3 2  1
    """
    print(maxOfLeftElement(root))
 
 

C#




// C# Program to print maximum element
// in left node
using System;
using System.Collections.Generic;
 
// a binary tree node
class Node{
    public int data;
    public Node left;
    public Node right;
 
    public Node(int data){
        this.data = data;
        left = null;
        right = null;
    }
}
 
class BinaryTree
{
   
    // get max of left element by
    // level order traversal using queue
    public static int maxOfLeftElement(Node root){
        int res = int.MinValue;
        if(root == null) return res;
        Queue<Node> q = new Queue<Node>();
        q.Enqueue(root);
        while(q.Count > 0){
            Node front_node = q.Dequeue();
            if(front_node.left != null){
                res = Math.Max(res, front_node.left.data);
            }
            if(front_node.left != null) q.Enqueue(front_node.left);
            if(front_node.right != null) q.Enqueue(front_node.right);
        }
        return res;
    }
 
    // Driver program to test above functions
    static void Main(){
        // Let us create binary tree shown in above diagram
        Node root = new Node(7);
        root.left = new Node(6);
        root.right = new Node(5);
        root.left.left = new Node(4);
        root.left.right = new Node(3);
        root.right.left = new Node(2);
        root.right.right = new Node(1);
  
        /*     7
             /    \
            6       5
           / \     / \
          4  3     2  1          */
        Console.WriteLine(maxOfLeftElement(root));
    }
}
 
 

Javascript




// javascript Program to print maximum element
// in left node
 
// a binary tree node
class Node{
     
    constructor(){
        this.data = 0;
        this.left = null;
        this.right = null;
    }
}
 
// utiltity function to create a new tree node
function newNode(data){
    let temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}
 
// get max of left element by
// level order traversal using queue
function maxOfLeftElement(root){
    let res = -2000;
    if(root == null) return res;
    let q = [];
    q.push(root);
     
    while(q.length > 0){
        let front_node = q[0];
        q.shift();
        if(front_node.left != null){
            res = Math.max(res, front_node.left.data);
        }
        if(front_node.left) q.push(front_node.left);
        if(front_node.right) q.push(front_node.right);
    }
    return res;
}
 
// Driver program to test above functions
// Let us create binary tree shown in above diagram
let root = newNode(7);
root.left = newNode(6);
root.right = newNode(5);
root.left.left = newNode(4);
root.left.right = newNode(3);
root.right.left = newNode(2);
root.right.right = newNode(1);
 
/*     7
     /    \
    6       5
   / \     / \
  4  3     2  1          */
console.log(maxOfLeftElement(root));
 
// The code is contributed by Nidhi goel.
 
 
Output
6

Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(N) due to queue data structure.



Next Article
Find maximum (or minimum) in Binary Tree
author
devanshuagarwal
Improve
Article Tags :
  • DSA
  • Tree
Practice Tags :
  • Tree

Similar Reads

  • 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, main
    13 min read
  • Find Minimum Depth of a Binary Tree
    Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum depth of below Binary Tree is 2. Note that the path must end on a leaf node. For example, the minimum depth of below Bi
    15 min read
  • Find maximum (or minimum) in Binary Tree
    Given a Binary Tree, find the maximum(or minimum) element in it. For example, maximum in the following Binary Tree is 9. Recommended PracticeMax and min element in Binary TreeTry It! In Binary Search Tree, we can find maximum by traversing right pointers until we reach the rightmost node. But in Bin
    8 min read
  • Delete the last leaf node in a Binary Tree
    Given a Binary Tree, the task is to find and DELETE the last leaf node.The leaf node is a node with no children. The last leaf node would be the node that is traversed last in sequence during Level Order Traversal. The problem statement is to identify this last visited node and delete this particula
    15+ min read
  • Count Non-Leaf nodes in a Binary Tree
    Given a Binary tree, count the total number of non-leaf nodes in the tree Examples: Input : Output :2 Explanation In the above tree only two nodes 1 and 2 are non-leaf nodesRecommended PracticeCount Non-Leaf Nodes in TreeTry It! We recursively traverse the given tree. While traversing, we count non-
    10 min read
  • Level of a Node in Binary Tree
    Given a Binary Tree and a key, the task is to find the level of key in the Binary Tree. Examples: Input : key = 4 Output: 3Explanation: The level of the key in above binary tree is 3.Input : key = 10 Output: -1Explanation: Key is not present in the above Binary tree. Table of Content [Expected Appro
    12 min read
  • Closest leaf to a given node in Binary Tree
    Given a Binary Tree and a node x in it, find distance of the closest leaf to x in Binary Tree. If given node itself is a leaf, then distance is 0.Examples: Input: Root of below tree And x = pointer to node 13 10 / \ 12 13 / 14 Output 1 Distance 1. Closest leaf is 14. Input: Root of below tree And x
    12 min read
  • Minimum in a Binary Search Tree
    Given the root of a Binary Search Tree. The task is to find the minimum valued element in this given BST. Example: Input: Output: 1Explanation: The minimum element in the given BST is 1. Input: Output: 2Explanation: The minimum element in the given BST is 2 Table of Content [Naive Approach] Using In
    12 min read
  • Sink even nodes in Binary Tree
    Given a Binary Tree having odd and even elements, sink all its even valued nodes such that no node with an even value could be a parent of a node with an odd value. There can be multiple outputs for a given tree, we need to print one of them. It is always possible to convert a tree (Note that a node
    13 min read
  • Find mirror of a given node in Binary tree
    Given a Binary tree, the problem is to find the mirror of a given node. The mirror of a node is a node which exists at the mirror position of the node in opposite subtree at the root. Examples: In above tree- Node 2 and 3 are mirror nodes Node 4 and 6 are mirror nodes. Recommended PracticeMirror of
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
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
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences