swoop

Recursive Tree

Feb 28th, 2012
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. package q1;
  2.  
  3. public class MinTree {
  4.  
  5.     Tree tree = new Tree( 24,
  6.                  new Tree( 45,
  7.                      null ,
  8.                      new Tree(8, null , null) ) ,
  9.                  new Tree ( 17,
  10.                      new Tree (74 , null , null ) ,
  11.                      null ) );
  12.  
  13.     public static void main(String[] args){
  14.     MinTree mt = new MinTree();
  15.     System.out.println("Minimum is :" + mt.findMin());
  16.     }
  17.  
  18.     public int findMin(){
  19.         return findMinAux(tree);
  20.  
  21.     }
  22.  
  23.     private int findMinAux(Tree t) {
  24.         int min;
  25.         int minL;
  26.         int minR;
  27.        
  28.         min = t.getVal();
  29.        
  30.         if(notEmpty(t.left())){
  31.             minL = findMinAux(t.left());
  32.         }
  33.         else{
  34.             minL = min;
  35.         }
  36.        
  37.         if(notEmpty(t.right())){
  38.             minR = findMinAux(t.right());
  39.         }
  40.         else{
  41.             minR=min;
  42.         }
  43.        
  44.         if(minL < min){
  45.             min = minL;
  46.         }
  47.        
  48.         if(minR < min){
  49.             min = minR;
  50.         }
  51.        
  52.         return min;
  53.     }
  54.    
  55.     private boolean notEmpty(Tree t){
  56.         if(t.equals(null)){
  57.             return false;
  58.         }
  59.         else{
  60.             return true;
  61.         }
  62.     }
  63.  
  64.    
  65. class Tree {
  66.  
  67.    private int val;
  68.    private Tree left, right;
  69.  
  70.    public Tree(int val, Tree left, Tree right){
  71.      this.val = val;
  72.      this.left = left;
  73.      this.right = right;
  74.    }
  75.  
  76.    public int getVal(){
  77.       return val;
  78.    }
  79.  
  80.    public Tree left(){
  81.       return left;
  82.    }
  83.  
  84.    public Tree right(){
  85.       return right;
  86.    }
  87. }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment