Open In App

Find the node with maximum value in a Binary Search Tree

Improve
Improve
Like Article
Like
Save
Share
Report

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


For the above tree, we start with 20, then we move right to 22. We keep on moving to the right until we see NULL. Since the right of 22 is NULL, 22 is the node with the maximum value.

Approach: This is quite simple. Just traverse the node from root to right recursively until the right is NULL. The node whose right is NULL is the node with the maximum value. 

C++

#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data, pointer to left child 
   and a pointer to right child */
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
// Function to create a new node
struct node* newNode(int data)
{
    struct node* newnode = new node();
    newnode->data = data;
    newnode->left = NULL;
    newnode->right = NULL;
 
    return (newnode);
}
 
// Function to insert a new node in BST
struct node* insert(struct node* node, int data)
{
    /* 1. If the tree is empty, return a new,     
      single node */
    if (node == NULL)
        return (newNode(data));
    else {
        /* 2. Otherwise, recur down the tree */
        if (data <= node->data)
            node->left = insert(node->left, data);
        else
            node->right = insert(node->right, data);
 
        /* return the (unchanged) node pointer */
        return node;
    }
}
 
// Function to find the node with maximum value
// i.e. rightmost leaf node
int maxValue(struct node* node)
{  
    /* loop down to find the rightmost leaf */
    struct node* current = node;
    while (current->right != NULL)
        current = current->right;
     
    return (current->data);
}
 
// Driver code
int main()
{
    struct node* root = NULL;
    root = insert(root, 4);
    insert(root, 2);
    insert(root, 1);
    insert(root, 3);
    insert(root, 6);
    insert(root, 5);
 
    cout << "Maximum value in BST is " << maxValue(root);
 
    return 0;
}

                    

Java

// Java Program to find the maximum element in the given BST
import java.util.*;
 
public class GFG {
    // A binary tree node
    static class node {
        int data;
        node left;
        node right;
    };
 
    // Function to create a new node
    static node newNode(int data){
        node node = new node();
        node.data = data;
        node.left = null;
        node.right = null;
        return node;
    }
 
    // Function to insert a new node in BST
    static node insert(node node, int data){
        // if tree is blank return a new node
        if (node == null)
            return (newNode(data));
        else{
            /* 2. Otherwise, recur down the tree */
            if (data <= node.data)
                node.left = insert(node.left, data);
            else
                node.right = insert(node.right, data);
            return node;
        }
    }
 
    // Function to find the node with maximum value
    // i.e. rightmost leaf node
    static int maxValue(node node){
        // loop to find the rightmost node of BST
        node current = node;
        while (current.right != null)
            current = current.right;
 
        return current.data;
    }
 
    // Driver code to test above function
    public static void main(String[] args){
        node root = null;
        root = insert(root, 4);
        insert(root, 2);
        insert(root, 1);
        insert(root, 3);
        insert(root, 6);
        insert(root, 5);
 
        System.out.println("Maximum value in BST is " + maxValue(root));
    }
}
// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL(KIRTIAGARWAL23121999)

                    

Python3

import sys
import math
 
# A binary tree node has data, pointer to left child
# and a pointer to right child
class Node:
    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to insert a new node in BST
def insert(root, data):
 
    # 1. If the tree is empty, return a new,    
    # single node
    if not root:
        return Node(data)
 
    # 2. Otherwise, recur down the tree
    if data < root.data:
        root.left = insert(root.left, data)
    if data > root.data:
        root.right = insert(root.right, data)
     
    # return the (unchanged) node pointer
    return root
 
# Function to find the node with maximum value
# i.e. rightmost leaf node
def maxValue(root):
    current = root
     
    #loop down to find the rightmost leaf
    while(current.right):
        current = current.right
    return current.data
 
# Driver code
if __name__=='__main__':
    root=None
    root = insert(root,2)
    root = insert(root,1)
    root = insert(root,3)
    root = insert(root,6)
    root = insert(root,5)
    print("Maximum value in BST is {}".format(maxValue(root)))
 
# This code is contributed by Vikash Kumar 37

                    

C#

// C# implementation to find the sum of last
// 'n' nodes of the Linked List
using System;
 
class GFG
{
 
 
/* A binary tree node has data, pointer to left child
and a pointer to right child */
public class node
{
    public int data;
    public node left;
    public node right;
};
 
// Function to create a new node
static node newNode(int data)
{
    node node = new node();
    node.data = data;
    node.left = null;
    node.right = null;
 
    return (node);
}
 
// Function to insert a new node in BST
static node insert(node node, int data)
{
    /* 1. If the tree is empty, return a new,
    single node */
    if (node == null)
        return (newNode(data));
    else
    {
        /* 2. Otherwise, recur down the tree */
        if (data <= node.data)
            node.left = insert(node.left, data);
        else
            node.right = insert(node.right, data);
 
        /* return the (unchanged) node pointer */
        return node;
    }
}
 
// Function to find the node with maximum value
// i.e. rightmost leaf node
static int maxValue(node node)
{
    /* loop down to find the rightmost leaf */
    node current = node;
    while (current.right != null)
        current = current.right;
     
    return (current.data);
}
 
// Driver code
public static void Main(String[] args)
{
    node root = null;
    root = insert(root, 4);
    insert(root, 2);
    insert(root, 1);
    insert(root, 3);
    insert(root, 6);
    insert(root, 5);
 
    Console.WriteLine("Maximum value in BST is " + maxValue(root));
}
}
 
// This code is contributed by Rajput-Ji

                    

Javascript

<script>
    // javascript implementation to find the sum of last
    // 'n' nodes of the Linked List
 
    /*
     * A binary tree node has data, pointer to left child and a pointer to right
     * child
     */
    class Node {
        constructor(val) {
            this.data = val;
            this.left = null;
            this.right = null;
        }
    }
 
    // Function to create a new node
     function newNode(data) {
        var node = new Node();
        node.data = data;
        node.left = null;
        node.right = null;
 
        return (node);
    }
 
    // Function to insert a new node in BST
     function insert( node , data) {
        /*
         * 1. If the tree is empty, return a new, single node
         */
        if (node == null)
            return (newNode(data));
        else {
            /* 2. Otherwise, recur down the tree */
            if (data <= node.data)
                node.left = insert(node.left, data);
            else
                node.right = insert(node.right, data);
 
            /* return the (unchanged) node pointer */
            return node;
        }
    }
 
    // Function to find the node with maximum value
    // i.e. rightmost leaf node
    function maxValue( node) {
        /* loop down to find the rightmost leaf */
        var current = node;
        while (current.right != null)
            current = current.right;
 
        return (current.data);
    }
 
    // Driver code
     
        var root = null;
        root = insert(root, 4);
        insert(root, 2);
        insert(root, 1);
        insert(root, 3);
        insert(root, 6);
        insert(root, 5);
 
        document.write("Maximum value in BST is " + maxValue(root));
 
// This code contributed by Rajput-Ji
</script>

                    

Output
Maximum value in BST is 6

Complexity Analysis:

  • Time Complexity: O(h), where h is the height of the BST.
  • Auxiliary Space: O(1)

Using Morris traversal:

The key idea behind the Morris Traversal approach is to use the right child of the predecessor to link back to the current node, so that we can move back up the tree after visiting the left subtree of the current node. This allows us to traverse the tree without using any extra space

Follow the steps below to implement the above idea:

  1. Initialize a variable max_val to store the maximum value seen so far, and a pointer curr to point to the current node.
  2. While curr is not NULL, do the following:
  3. If the left subtree of curr is NULL, update max_val with the value of curr, and move to the right subtree of curr.
  4. If the left subtree of curr is not NULL, find the predecessor of curr in its left subtree. The predecessor is the rightmost node in the left subtree of curr.
  5. If the right child of the predecessor is NULL, set it to curr and move to the left child of curr.
  6. If the right child of the predecessor is curr, restore it to NULL, update max_val with the value of curr, and move to the right child of curr.
  7. Return max_val.

Implementation:

C++

//C++ code to implement the morris traversal approach
#include <climits>
#include <iostream>
 
using namespace std;
 
// Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x)
        : val(x)
        , left(NULL)
        , right(NULL)
    {
    }
};
 
int findMaxNode(TreeNode* root)
{
    int max_val = INT_MIN;
    TreeNode* curr = root;
    while (curr != NULL) {
        if (curr->left == NULL) {
            // If the left subtree is NULL, update the
            // maximum value seen so far
            max_val = max(max_val, curr->val);
            curr = curr->right; // Visit the right subtree
        }
        else {
            // Find the predecessor of the current node
            TreeNode* pred = curr->left;
            while (pred->right != NULL
                   && pred->right != curr) {
                pred = pred->right;
            }
            if (pred->right == NULL) {
                // Set the predecessor's right child to the
                // current node
                pred->right = curr;
                curr = curr->left; // Visit the left subtree
            }
            else {
                // The predecessor's right child is already
                // set to the current node, indicating that
                // we have visited the left subtree of the
                // current node
                pred->right
                    = NULL; // Restore the predecessor's
                            // right child
                max_val
                    = max(max_val,
                          curr->val); // Update the maximum
                                      // value seen so far
                curr = curr->right; // Visit the right
                                    // subtree
            }
        }
    }
    return max_val;
}
 
int main()
{
    /* Create a binary search tree
 
          8
        /   \
       3    10
      / \     \
     1   6    14
        / \   /
       4   7 13
    */
 
    TreeNode* root = new TreeNode(8);
    root->left = new TreeNode(3);
    root->left->left = new TreeNode(1);
    root->left->right = new TreeNode(6);
    root->left->right->left = new TreeNode(4);
    root->left->right->right = new TreeNode(7);
    root->right = new TreeNode(10);
    root->right->right = new TreeNode(14);
    root->right->right->left = new TreeNode(13);
 
    // Find the node with maximum value in the binary search
    // tree
    int max_val = findMaxNode(root);
 
    // Output the result
    cout << "The node with maximum value in the binary "
            "search tree is "
         << max_val << endl;
 
    return 0;
}
// This code is contributed by Veerendra_Singh_Rajpoot

                    

Java

import java.lang.*;
 
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
 
    TreeNode(int val)
    {
        this.val = val;
        this.left = null;
        this.right = null;
    }
 
    TreeNode(int val, TreeNode left, TreeNode right)
    {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
 
class Main {
    public static int findMaxNode(TreeNode root)
    {
        int max_val = -Integer.MAX_VALUE;
        TreeNode curr = root;
        while (curr != null) {
            if (curr.left == null) {
                // If the left subtree is null, update the
                // maximum value seen so far
                max_val = Math.max(max_val, curr.val);
                curr
                    = curr.right; // Visit the right subtree
            }
            else {
                // Find the predecessor of the current node
                TreeNode pred = curr.left;
                while (pred.right != null
                       && pred.right != curr) {
                    pred = pred.right;
                }
                if (pred.right == null) {
                    // Set the predecessor's right child to
                    // the current node
                    pred.right = curr;
                    curr = curr.left; // Visit the left
                                      // subtree
                }
                else {
                    // The predecessor's right child is
                    // already set to the current node,
                    // indicating that we have visited the
                    // left subtree of the current node
                    pred.right
                        = null; // Restore the predecessor's
                                // right child
                    max_val = Math.max(
                        max_val,
                        curr.val); // Update the maximum
                                   // value seen so far
                    curr = curr.right; // Visit the right
                                       // subtree
                }
            }
        }
        return max_val;
    }
 
    public static void main(String[] args)
    {
        // Create a binary search tree
        /*
              8
            /   \
           3    10
          / \     \
         1   6    14
            / \   /
           4   7 13
        */
        TreeNode root = new TreeNode(8);
        root.left = new TreeNode(3);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(6);
        root.left.right.left = new TreeNode(4);
        root.left.right.right = new TreeNode(7);
        root.right = new TreeNode(10);
        root.right.right = new TreeNode(14);
        root.right.right.left = new TreeNode(13);
 
        // Find the node with maximum value in binary search
        // tree
        int max_val = findMaxNode(root);
        System.out.println(
            "The node with maximum value in the binary search tree is "
            + findMaxNode(root));
    }
}

                    

Python3

import sys
 
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val = 0, left = None, right = None):
        self.val = val
        self.left = left
        self.right = right
 
def findMaxNode(root: TreeNode) -> int:
    max_val = -sys.maxsize
    curr = root
    while curr:
        if not curr.left:
            # If the left subtree is None, update the
            # maximum value seen so far
            max_val = max(max_val, curr.val)
            curr = curr.right  # Visit the right subtree
        else:
            # Find the predecessor of the current node
            pred = curr.left
            while pred.right and pred.right != curr:
                pred = pred.right
            if not pred.right:
                # Set the predecessor's right child to the
                # current node
                pred.right = curr
                curr = curr.left  # Visit the left subtree
            else:
                # The predecessor's right child is already
                # set to the current node, indicating that
                # we have visited the left subtree of the
                # current node
                pred.right = None  # Restore the predecessor's
                                   # right child
                max_val = max(max_val, curr.val)  # Update the maximum
                                                 # value seen so far
                curr = curr.right  # Visit the right subtree
    return max_val
 
if __name__ == '__main__':
    # Create a binary search tree
    """
          8
        /   \
       3    10
      / \     \
     1   6    14
        / \   /
       4   7 13
    """
    root = TreeNode(8)
    root.left = TreeNode(3)
    root.left.left = TreeNode(1)
    root.left.right = TreeNode(6)
    root.left.right.left = TreeNode(4)
    root.left.right.right = TreeNode(7)
    root.right = TreeNode(10)
    root.right.right = TreeNode(14)
    root.right.right.left = TreeNode(13)
 
    # Find the node with maximum value in the binary search
    # tree
    max_val = findMaxNode(root)
 
    # Output the result
    print(f"The node with maximum value in the binary search tree is {max_val}")

                    

C#

using System;
 
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
 
    public TreeNode(int x)
    {
        val = x;
        left = null;
        right = null;
    }
}
 
public class Program {
    public static int FindMaxNode(TreeNode root)
    {
        int max_val = int.MinValue;
        TreeNode curr = root;
 
        while (curr != null) {
            if (curr.left == null) {
                // If the left subtree is NULL, update the
                // maximum value seen so far
                max_val = Math.Max(max_val, curr.val);
                curr
                    = curr.right; // Visit the right subtree
            }
            else {
                // Find the predecessor of the current node
                TreeNode pred = curr.left;
 
                while (pred.right != null
                       && pred.right != curr) {
                    pred = pred.right;
                }
 
                if (pred.right == null) {
                    // Set the predecessor's right child to
                    // the current node
                    pred.right = curr;
                    curr = curr.left; // Visit the left
                                      // subtree
                }
                else {
                    // The predecessor's right child is
                    // already set to the current node,
                    // indicating that we have visited the
                    // left subtree of the current node
                    pred.right
                        = null; // Restore the predecessor's
                                // right child
                    max_val = Math.Max(
                        max_val,
                        curr.val); // Update the maximum
                                   // value seen so far
                    curr = curr.right; // Visit the right
                                       // subtree
                }
            }
        }
 
        return max_val;
    }
 
    public static void Main()
    {
        /* Create a binary search tree
               8
             /   \
            3     10
           / \      \
          1   6      14
             / \     /
            4   7   13 */
        TreeNode root = new TreeNode(8);
        root.left = new TreeNode(3);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(6);
        root.left.right.left = new TreeNode(4);
        root.left.right.right = new TreeNode(7);
        root.right = new TreeNode(10);
        root.right.right = new TreeNode(14);
        root.right.right.left = new TreeNode(13);
 
        // Find the node with maximum value in the binary
        // search tree
        int max_val = FindMaxNode(root);
 
        // Output the result
        Console.WriteLine("The node with maximum value in "
                          + "the binary search tree is "
                          + max_val);
    }
}

                    

Javascript

class TreeNode {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}
 
function findMaxNode(root) {
    let maxVal = -Infinity;
    let curr = root;
 
    while (curr !== null) {
        if (curr.left === null) {
            // If the left subtree is null, update the maximum value seen so far
            maxVal = Math.max(maxVal, curr.val);
            curr = curr.right; // Visit the right subtree
        } else {
            // Find the predecessor of the current node
            let pred = curr.left;
            while (pred.right !== null && pred.right !== curr) {
                pred = pred.right;
            }
            if (pred.right === null) {
                // Set the predecessor's right child to the current node
                pred.right = curr;
                curr = curr.left; // Visit the left subtree
            } else {
                // The predecessor's right child is already set to the current node,
                // indicating that we have visited the left subtree of the current node
                pred.right = null; // Restore the predecessor's right child
                maxVal = Math.max(maxVal, curr.val); // Update the maximum value seen so far
                curr = curr.right; // Visit the right subtree
            }
        }
    }
 
    return maxVal;
}
 
// Create a binary search tree
/*
          8
        /   \
       3    10
      / \     \
     1   6    14
        / \   /
       4   7 13
*/
const root = new TreeNode(8);
root.left = new TreeNode(3);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(6);
root.left.right.left = new TreeNode(4);
root.left.right.right = new TreeNode(7);
root.right = new TreeNode(10);
root.right.right = new TreeNode(14);
root.right.right.left = new TreeNode(13);
 
// Find the node with maximum value in the binary search tree
const maxVal = findMaxNode(root);
 
// Output the result
console.log("The node with maximum value in the binary search tree is " + maxVal);

                    

Output
The node with maximum value in the binary search tree is 14

Time Complexity: O(n),In the worst case, the algorithm visits every node in the binary search tree once.
At each node, the algorithm performs a constant amount of work to find the predecessor node and update the temporary links.
Therefore, the time complexity of the Morris Traversal approach is O(n), where n is the number of nodes in the binary search tree.
Space Complexity: O(1)The Morris Traversal approach uses only a constant amount of extra space to store the temporary links between some nodes.
Therefore, the space complexity of the Morris Traversal approach is O(1)



Last Updated : 02 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads