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:
Maximum spiral sum in Binary Tree
Next article icon

Maximum in a Binary Search Tree

Last Updated : 08 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Search Tree, the task is to find the node with the maximum value in a BST.

Example:

Input:
ex-1

Output : 7

Input:
ex-2

Output: 20

Table of Content

  • [Naive Approach] Using Inorder Traversal – O(n) Time and O(n) Space
  • [Expected Approach] Iterative Approach – O(n) Time and O(1) Space

[Naive Approach] Using Inorder Traversal – O(n) Time and O(n) Space

The idea is to use the property of BST which says inorder traversal of a binary search tree always returns the value of nodes in sorted order. So the last value in the sorted vector will be the maximumvalue which is the answer. 

Below is the implementation of the above approach:

C++
#include <iostream> #include <vector> using namespace std;  class Node { public:     int data;     Node* left;     Node* right;     Node(int val) : data(val), left(nullptr), right(nullptr) {} };  void inorder(Node* root, vector<int>& sorted_inorder) {          if (root == nullptr) return;      // Traverse left subtree     inorder(root->left, sorted_inorder);      // Store the current node's data     sorted_inorder.push_back(root->data);      // Traverse right subtree     inorder(root->right, sorted_inorder); }  int maxValue(Node* root) {     if (root == nullptr) return -1;      // Using a vector to hold inorder elements     vector<int> sorted_inorder;      // Call the recursive inorder function     inorder(root, sorted_inorder);      // Return the last element, which is the maximum     return sorted_inorder.back(); }  int main() {     // Representation of input binary search tree     //        5     //       / \     //      4   6     //     /     \     //    3       7     //   /       //  1     Node* root = new Node(5);     root->left = new Node(4);     root->right = new Node(6);     root->left->left = new Node(3);     root->right->right = new Node(7);     root->left->left->left = new Node(1);      cout << maxValue(root) << endl;     return 0; } 
C
#include <stdio.h> #include <stdlib.h>  struct Node {     int data;     struct Node* left;     struct Node* right; };  void inorder(struct Node* root, int* sorted_inorder, int* index) {     // Base Case     if (root == NULL) {         return;     }      // Traverse left subtree     inorder(root->left, sorted_inorder, index);      // Store the current node's data     sorted_inorder[(*index)++] = root->data;      // Traverse right subtree     inorder(root->right, sorted_inorder, index); }  int maxValue(struct Node* root) {     if (root == NULL) {         return -1;     }      // Using an array to hold inorder elements     int sorted_inorder[100]; // Assuming a maximum of 100 nodes     int index = 0;      // Call the recursive inorder function     inorder(root, sorted_inorder, &index);      // Return the last element, which is the maximum     return sorted_inorder[index - 1]; }  int main() {     // Representation of input binary search tree     //        5     //       / \     //      4   6     //     /     \     //    3       7     //   /       //  1     struct Node* root = (struct Node*)malloc(sizeof(struct Node));     root->data = 5;     root->left = (struct Node*)malloc(sizeof(struct Node));     root->left->data = 4;     root->right = (struct Node*)malloc(sizeof(struct Node));     root->right->data = 6;     root->left->left = (struct Node*)malloc(sizeof(struct Node));     root->left->left->data = 3;     root->right->right = (struct Node*)malloc(sizeof(struct Node));     root->right->right->data = 7;     root->left->left->left = (struct Node*)malloc(sizeof(struct Node));     root->left->left->left->data = 1;      printf("%d\n", maxValue(root));      return 0; } 
Java
class Node {     int data;     Node left, right;      Node(int item) {         data = item;         left = right = null;     } }  public class BinaryTree {     Node root;      void inorder(Node node, List<Integer> sortedInorder) {         // Base Case         if (node == null) {             return;         }          // Traverse left subtree         inorder(node.left, sortedInorder);          // Store the current node's data         sortedInorder.add(node.data);          // Traverse right subtree         inorder(node.right, sortedInorder);     }      int maxValue(Node node) {         if (node == null) {             return -1;         }          // Using a list to hold inorder elements         List<Integer> sortedInorder = new ArrayList<>();          // Call the recursive inorder function         inorder(node, sortedInorder);          // Return the last element, which is the maximum         return sortedInorder.get(sortedInorder.size() - 1);     }      public static void main(String[] args) {         BinaryTree tree = new BinaryTree();         // Representation of input binary search tree         //        5         //       / \         //      4   6         //     /     \         //    3       7         //   /           //  1         tree.root = new Node(5);         tree.root.left = new Node(4);         tree.root.right = new Node(6);         tree.root.left.left = new Node(3);         tree.root.right.right = new Node(7);         tree.root.left.left.left = new Node(1);          System.out.println(tree.maxValue(tree.root));     } } 
Python
class Node:     def __init__(self, data):         self.data = data         self.left = None         self.right = None  def inorder(root, sorted_inorder):        # Base Case     if root is None:         return      # Traverse left subtree     inorder(root.left, sorted_inorder)      # Store the current node's data     sorted_inorder.append(root.data)      # Traverse right subtree     inorder(root.right, sorted_inorder)  def maxValue(root):     if root is None:         return -1      # Using a list to hold inorder elements     sorted_inorder = []        # Call the recursive inorder function     inorder(root, sorted_inorder)      # Return the last element, which is the maximum     return sorted_inorder[-1]  if __name__ == "__main__":      # Representation of input binary search tree     #        5     #       / \     #      4   6     #     /     \     #    3       7     #   /       #  1     root = Node(5)     root.left = Node(4)     root.right = Node(6)     root.left.left = Node(3)     root.right.right = Node(7)     root.left.left.left = Node(1)      print(maxValue(root))   
C#
using System; using System.Collections.Generic;  class Node {     public int data;     public Node left;     public Node right;      public Node(int data) {         this.data = data;         this.left = null;         this.right = null;     } }  class Program {     static void Inorder(Node root, List<int> sortedInorder) {         // Base Case         if (root == null) {             return;         }          // Traverse left subtree         Inorder(root.left, sortedInorder);          // Store the current node's data         sortedInorder.Add(root.data);          // Traverse right subtree         Inorder(root.right, sortedInorder);     }      static int MaxValue(Node root) {         if (root == null) {             return -1;         }          // Using a list to hold inorder elements         List<int> sortedInorder = new List<int>();          // Call the recursive inorder function         Inorder(root, sortedInorder);          // Return the last element, which is the maximum         return sortedInorder[sortedInorder.Count - 1];     }      static void Main() {         // Representation of input binary search tree         //        5         //       / \         //      4   6         //     /     \         //    3       7         //   /           //  1         Node root = new Node(5);         root.left = new Node(4);         root.right = new Node(6);         root.left.left = new Node(3);         root.right.right = new Node(7);         root.left.left.left = new Node(1);          Console.WriteLine(MaxValue(root));     } } 
JavaScript
class Node {     constructor(data) {         this.data = data;         this.left = null;         this.right = null;     } }  function inorder(root, sorted_inorder) {     // Base Case     if (root === null) {         return;     }      // Traverse left subtree     inorder(root.left, sorted_inorder);      // Store the current node's data     sorted_inorder.push(root.data);      // Traverse right subtree     inorder(root.right, sorted_inorder); }  function maxValue(root) {     if (root === null) {         return -1;     }      // Using an array to hold inorder elements     let sorted_inorder = [];      // Call the recursive inorder function     inorder(root, sorted_inorder);      // Return the last element, which is the maximum     return sorted_inorder[sorted_inorder.length - 1]; }  // Representation of input binary search tree //        5 //       / \ //      4   6 //     /     \ //    3       7 //   /   //  1 let root = new Node(5); root.left = new Node(4); root.right = new Node(6); root.left.left = new Node(3); root.right.right = new Node(7); root.left.left.left = new Node(1);  console.log(maxValue(root)); 

Output
7 

Time Complexity: O(n), where n is the number of nodes in BST.
Auxiliary Space: O(n)

[Expected Approach] Traversing Across Right Edges Only – O(h) Time and O(1) Space

The idea is that in a Binary Search Tree (BST), the right child of a node is always larger than the root. This ensures that the node whose right pointer is NULL must hold the maximum value in the tree. The rightmost node will always contain the largest element.

Below is the implementation of the above approach:

C++
#include <iostream> using namespace std;  class Node { public:     int data;     Node* left;     Node* right;     Node(int value) : data(value), left(NULL), right(NULL) {} };  // Function to find the maximum value in BST int maxValue(Node* root) {     // Base case     if (root == NULL) {         return -1;     }      Node* curr = root;      // Rightmost node is maximum, so move      // till right is not NULL     while (curr->right != NULL) {         curr = curr->right;     }      // Returning the data at the rightmost node     return curr->data; }  int main() {     // Representation of input binary search tree     //        5     //       / \     //      4   6     //     /     \     //    3       7     //   /       //  1     Node* root = new Node(5);     root->left = new Node(4);     root->right = new Node(6);     root->left->left = new Node(3);     root->right->right = new Node(7);     root->left->left->left = new Node(1);      cout << maxValue(root) << endl;     return 0; } 
C
#include <stdio.h> #include <stdlib.h>  struct Node {     int data;     struct Node* left;     struct Node* right; };  // Function to find the maximum value in BST int maxValue(struct Node* root) {     // Base case     if (root == NULL) {         return -1;     }      struct Node* curr = root;      // Rightmost node is maximum, so move      // till right is not NULL     while (curr->right != NULL) {         curr = curr->right;     }      // Returning the data at the rightmost node     return curr->data; }  int main() {     // Representation of input binary search tree     //        5     //       / \     //      4   6     //     /     \     //    3       7     //   /       //  1     struct Node* root = (struct Node*)malloc(sizeof(struct Node));     root->data = 5;     root->left = (struct Node*)malloc(sizeof(struct Node));     root->left->data = 4;     root->right = (struct Node*)malloc(sizeof(struct Node));     root->right->data = 6;     root->left->left = (struct Node*)malloc(sizeof(struct Node));     root->left->left->data = 3;     root->right->right = (struct Node*)malloc(sizeof(struct Node));     root->right->right->data = 7;     root->left->left->left = (struct Node*)malloc(sizeof(struct Node));     root->left->left->left->data = 1;      printf("%d\n", maxValue(root));     return 0; } 
Java
class Node {     int data;     Node left, right;      Node(int value) {         data = value;         left = right = null;     } }  // Function to find the maximum value in BST int maxValue(Node root) {     // Base case     if (root == null) {         return -1;     }      Node curr = root;      // Rightmost node is maximum, so move      // till right is not null     while (curr.right != null) {         curr = curr.right;     }      // Returning the data at the rightmost node     return curr.data; }  public static void main(String[] args) {     // Representation of input binary search tree     //        5     //       / \     //      4   6     //     /     \     //    3       7     //   /       //  1     Node root = new Node(5);     root.left = new Node(4);     root.right = new Node(6);     root.left.left = new Node(3);     root.right.right = new Node(7);     root.left.left.left = new Node(1);      System.out.println(maxValue(root)); } 
Python
class Node:     def __init__(self, data):         self.data = data         self.left = None         self.right = None  # Function to find the maximum value in BST def maxValue(root):     # Base case     if root is None:         return -1      curr = root      # Rightmost node is maximum, so move      # till right is not None     while curr.right is not None:         curr = curr.right      # Returning the data at the rightmost node     return curr.data  if __name__ == "__main__":      # Representation of input binary search tree     #        5     #       / \     #      4   6     #     /     \     #    3       7     #   /       #  1     root = Node(5)     root.left = Node(4)     root.right = Node(6)     root.left.left = Node(3)     root.right.right = Node(7)     root.left.left.left = Node(1)      print(maxValue(root))   
C#
using System;  class Node {     public int data;     public Node left, right;      public Node(int value) {         data = value;         left = right = null;     } }  // Function to find the maximum value in BST public static int maxValue(Node root) {     // Base case     if (root == null) {         return -1;     }      Node curr = root;      // Rightmost node is maximum, so move      // till right is not null     while (curr.right != null) {         curr = curr.right;     }      // Returning the data at the rightmost node     return curr.data; }  public static void Main() {     // Representation of input binary search tree     //        5     //       / \     //      4   6     //     /     \     //    3       7     //   /       //  1     Node root = new Node(5);     root.left = new Node(4);     root.right = new Node(6);     root.left.left = new Node(3);     root.right.right = new Node(7);     root.left.left.left = new Node(1);      Console.WriteLine(maxValue(root)); } 
JavaScript
// Node class definition class Node {     constructor(data) {         this.data = data;         this.left = null;         this.right = null;     } }  // Function to find the maximum value in BST function maxValue(root) {     // Base case     if (root === null) {         return -1;     }      let curr = root;      // Rightmost node is maximum, so move      // till right is not null     while (curr.right !== null) {         curr = curr.right;     }      // Returning the data at the rightmost node     return curr.data; }  // Representation of input binary search tree //        5 //       / \ //      4   6 //     /     \ //    3       7 //   /   //  1 let root = new Node(5); root.left = new Node(4); root.right = new Node(6); root.left.left = new Node(3); root.right.right = new Node(7); root.left.left.left = new Node(1);  console.log(maxValue(root)); 

Output
7 

Time Complexity: O(h) In the worst case where h is the height of the Binary Search Tree
Auxiliary Space: O(1)



Next Article
Maximum spiral sum in Binary Tree

V

VishalBachchas
Improve
Article Tags :
  • Binary Search Tree
  • Data Structures
  • DSA
  • Technical Scripter
  • Tree
  • Technical Scripter 2018
Practice Tags :
  • Binary Search Tree
  • Data Structures
  • Tree

Similar Reads

  • Maximum Path Sum in a Binary Tree
    Given a binary tree, the task is to find the maximum path sum. The path may start and end at any node in the tree. Example: Input: Output: 42Explanation: Max path sum is represented using green colour nodes in the above binary tree. Input: Output: 31Explanation: Max path sum is represented using gre
    9 min read
  • Maximum spiral sum in Binary Tree
    Given a binary tree containing n nodes. The task is to find the maximum sum obtained when the tree is spirally traversed. In spiral traversal one by one all levels are being traversed with the root level traversed from right to left, then the next level from left to right, then further next level fr
    9 min read
  • Find Mode in Binary Search tree
    Given a Binary Search Tree, find the mode of the tree. Note: Mode is the value of the node which has the highest frequency in the binary search tree. Examples: Input: 100 / \ 50 160 / \ / \ 50 60 140 170 Output: The mode of BST is 50Explanation: 50 is repeated 2 times, and all other nodes occur only
    10 min read
  • Optimal Binary Search Tree
    Given a sorted array key [0.. n-1] of search keys and an array freq[0.. n-1] of frequency counts, where freq[i] is the number of searches for keys[i]. Construct a binary search tree of all keys such that the total cost of all the searches is as small as possible. The cost of a BST node is the level
    15+ min read
  • Maximum Path sum in a N-ary Tree
    Given an undirected tree with n nodes numbered from 1 to n and an array arr[] where arr[i] denotes the value assigned to (i+1)th node. The connections between the nodes are provided in a 2-dimensional array edges[][]. The task is to find the maximum path sum between any two nodes. (Both the nodes ca
    7 min read
  • Maximum XOR path of a Binary Tree
    Given a Binary Tree, the task is to find the maximum of all the XOR value of all the nodes in the path from the root to leaf.Examples: Input: 2 / \ 1 4 / \ 10 8 Output: 11 Explanation: All the paths are: 2-1-10 XOR-VALUE = 9 2-1-8 XOR-VALUE = 11 2-4 XOR-VALUE = 6 Input: 2 / \ 1 4 / \ / \ 10 8 5 10 O
    8 min read
  • Binary Search Tree In Python
    A Binary search tree is a binary tree where the values of the left sub-tree are less than the root node and the values of the right sub-tree are greater than the value of the root node. In this article, we will discuss the binary search tree in Python. What is a Binary Search Tree(BST)?A Binary Sear
    11 min read
  • Binary Search Tree
    A Binary Search Tree (or BST) is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right chi
    3 min read
  • Get maximum left node in binary tree
    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 no
    10 min read
  • Maximum width of a Binary Tree
    Given a binary tree, the task is to find the maximum width of the given tree. The width of a tree is the maximum of the widths of all levels. Before solving the problem first, let us understand what we have to do. Binary trees are one of the most common types of trees in computer science. They are a
    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