Advertisement
Guest User

Untitled

a guest
Apr 20th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. public class BinTree {
  2.  
  3.     private int root;
  4.     private BinTree left;
  5.     private BinTree right;
  6.     private boolean empty = false;
  7.  
  8.     public BinTree(int rt, BinTree l, BinTree r) {
  9.         root = rt;
  10.         left = l;
  11.         right = r;
  12.     }
  13.  
  14.     public BinTree() {
  15.         empty = true;
  16.     }
  17.  
  18.     public BinTree(double p) {
  19.         if (Math.random() < p) {
  20.             empty = true;
  21.         } else {
  22.             root = (int)(Math.random()*100);
  23.             left = new BinTree(p*1.1);
  24.             right = new BinTree(p*1.1);
  25.         }
  26.     }
  27.  
  28.     public boolean isEmpty() {
  29.         return empty;
  30.     }
  31.  
  32.     public int size() {
  33.         if(isEmpty() == true) {
  34.             return 0;
  35.         } else {
  36.             return left.size() + right.size() + 1;
  37.         }
  38.     }
  39.  
  40.     public int height() {
  41.         if(isEmpty()) {
  42.             return -1;
  43.         } else {
  44.             return 1 + Math.max(left.height(), right.height());
  45.         }
  46.     }
  47.  
  48.     public int leaves() {
  49.         if (isEmpty()){
  50.             return 0;
  51.         }else if(height()==0){
  52.             return 1;
  53.         }else{
  54.             return left.leaves() + right.leaves();
  55.         }
  56.     }
  57.  
  58.     public boolean search(int n) {
  59.         if (isEmpty()){
  60.             return false;
  61.         }else{
  62.             return root == n||left.search(n)||right.search(n);
  63.         }
  64.     }
  65.  
  66.     public void print() {
  67.         if (!isEmpty()){
  68.             left.print();
  69.             right.print();
  70.             System.out.println(root);
  71.  
  72.         }
  73.     }
  74.  
  75.     public boolean perfect(){
  76.         if(isEmpty()){
  77.             return true;
  78.         }else{
  79.             return left.height() == right.height() &&
  80.             left.perfect() && right.perfect();
  81.         }
  82.     }
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement