Friday, 2 March 2018

Java Program to Find the Maximum and Minimum Values in a Binary Search Tree (BST)

          In the previous post, we discussed how to delete a node from a Binary Search Tree (BST). In this post, we will learn how to find the minimum and maximum values in a Binary Search Tree.

Keep in mind: In a BST, the value of every node in the left subtree is less than or equal to the value of the root node, and the value of every node in the right subtree is greater than the value of the root node.

To find the minimum value in a BST, simply traverse the left child of each node until you reach the leftmost node. The leftmost node contains the minimum value.

Similarly, to find the maximum value, traverse the right child of each node until you reach the rightmost node. The rightmost node contains the maximum value.

Consider the following BST:

Min and Max value in BST
Minimum and Maximum value in BST


MaxMinBSTNode.java

package com.test;

public class Node {

        Integer data;
        Node leftChild;
        Node rightChild;
 
        public Node(Integer data) {
              this.data = data;
              leftChild = null;
              rightChild = null;
        }
}


public class MaxMinBSTNode {
 
        Node root;

        private Integer getMaxNode() {
               return getMaxNode(root);
        }
 
        private Integer getMinNode() {
               return getMinNode(root);
        }
 
        private Integer getMaxNode(Node node) {
  
               if (node.rightChild != null) {
                      return getMaxNode(node.rightChild);
               } 
               return node.data;
        }
 
        private Integer getMinNode(Node node) {
               if(node.leftChild != null) {
                      return getMinNode(node.leftChild);
               }
               return node.data;
        }
 
        public static void main(String[] args) {
  
                 MaxMinBSTNode tree = new MaxMinBSTNode();
                 tree.root = new Node(22);
                 tree.root.leftChild = new Node(10);
                 tree.root.rightChild = new Node(30);
                 tree.root.leftChild.leftChild = new Node(6);
                 tree.root.leftChild.rightChild = new Node(14);
                 tree.root.rightChild.leftChild = new Node(27);
                 tree.root.rightChild.rightChild = new Node(32);
  
                 System.out.println("Max value:--"+tree.getMaxNode());
                 System.out.println("Min value:--"+tree.getMinNode());
        }
}

Output:-- Max value:-- 32
                 Min value:--6



Related Post:--
1) Java Program to delete a node from Binary Search Tree(BST)
2) Java Program to Count the number of nodes and leaf nodes of Binary Tree
3) Java Program to Reverse a Linked List using Recursion and Loops
4) How to Remove duplicates from ArrayList in Java
5) Java Program to Count Occurrence of Word in a Sentence

No comments:

Post a Comment