• Java Data Structures Tutorial

Searching for minimum value in a tree



To find the minimum value of a tree (without child nodes) compare the left node and right node and get the larger value (store it in max) then, compare it with the value of the root

If the result (min) is smaller then, it is the minimum value else, the root is the minimum value of the tree.

To get the minimum value of a whole binary tree get the minimum value of the left subtree, the minimum value of the right subtree and, the root. Now compare three of them smaller value among these three is the minimum value of the tree.

Example

class Node{
   int data;
   Node leftNode, rightNode;
   
   Node() {
      leftNode = null;
      rightNode = null;     
      this.data = data;
   }
   Node(int data) {
      leftNode = null;
      rightNode = null;     
      this.data = data;
   }
   int getData() {
      return this.data;	   
   }
   Node getleftNode() {
      return this.leftNode;      
   }
   Node getRightNode() {
      return this.leftNode;      
   }
   void setData(int data) {
      this.data = data; 
   }
   void setleftNode(Node leftNode) {
      this.leftNode = leftNode;      
   }
   void setRightNode(Node rightNode) {
      this.leftNode = rightNode;         
   }
}
public class MinValueInBinaryTree {
   public static void main(String[] args) {
      Node node = new Node(50);
      node.leftNode = new Node(60);
      node.leftNode.leftNode = new Node(45);
      node.leftNode.rightNode = new Node(64);

      node.rightNode = new Node(60);
      node.rightNode.leftNode = new Node(45);
      node.rightNode.rightNode = new Node(64);
      
      System.out.println("Minimum value is "+minimumValue(node));
   }   
   public static int minimumValue(Node root) {
      int min = 10000;      
      
      if(root!=null) {
         int lMin = minimumValue(root.leftNode);
         int rMin = minimumValue(root.rightNode);;
   
         if(lMin>rMin) {
            min = lMin;
         } else {
            min = rMin;           
         }

         if(root.data<min) {
            min = root.data;
         }
      }
      return min;
   }
}

Output

Minimum value is 50
Advertisements