Advertisement
saltycracker

Node.java

Sep 28th, 2020 (edited)
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.01 KB | None | 0 0
  1. package myBtree;
  2.  
  3. import java.util.function.Consumer;
  4. import java.util.Optional;
  5.  
  6. final public class Node<T extends Comparable<T>> extends Btree<T> {
  7.  
  8.   private final T data;
  9.   private final Btree<T> left;
  10.   private final Btree<T> right;
  11.  
  12.   protected Node(T data, Btree<T> left, Btree<T> right) {
  13.     this.data = data;
  14.     this.left = left;
  15.     this.right = right;
  16.   }
  17.  
  18.   @Override
  19.   public void display(Consumer<T> func) {
  20.     this.left.display(func);
  21.     func.accept(this.data);
  22.     this.right.display(func);
  23.   }
  24.  
  25.   @Override
  26.   public Btree<T> add(T data) {
  27.     final int ans = this.data.compareTo(data);
  28.     if (ans > 0) {
  29.       return new Node<T>(this.data, this.left.add(data), this.right);
  30.     }else if (ans < 0) {
  31.       return new Node<T>(this.data, this.left, this.right.add(data));
  32.     }else {
  33.       return this;
  34.     }
  35.   }
  36.  
  37.   @Override
  38.   public Optional<Btree<T>> find(T data) {
  39.     final int ans = this.data.compareTo(data);
  40.     if (ans > 0) {
  41.       return this.left.find(data);
  42.     }else if (ans < 0) {
  43.       return this.right.find(data);
  44.     }else {
  45.       return Optional.of(this);
  46.     }
  47.   }
  48.  
  49.   @Override
  50.   public boolean isEmpty() {
  51.     return false;
  52.   }
  53.  
  54.   private Btree<T> joinBranches(Btree<T> left, Btree<T> right) {
  55.     if (right.isEmpty()) {
  56.       return left;
  57.     }else {
  58.       return
  59.         new Node<T>(
  60.           ((Node<T>)right).data,
  61.           joinBranches(left, ((Node<T>)right).left),
  62.           ((Node<T>)right).right
  63.         );
  64.     }
  65.   }
  66.  
  67.   @Override
  68.   public Btree<T> remove(T data) {
  69.     final int ans = this.data.compareTo(data);
  70.     if (ans > 0) {
  71.       return new Node<T>(this.data, this.left.remove(data), this.right);
  72.     }else if (ans < 0) {
  73.       return new Node<T>(this.data, this.left, this.right.remove(data));
  74.     }else {
  75.       if (this.left.isEmpty()) {
  76.         return this.right;
  77.       }else if (this.right.isEmpty()) {
  78.         return this.left;
  79.       }else {
  80.         return joinBranches(this.left, this.right);
  81.       }
  82.     }
  83.   }
  84. }
  85.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement