package myBtree; import java.util.function.Consumer; import java.util.Optional; final public class Node> extends Btree { private final T data; private final Btree left; private final Btree right; protected Node(T data, Btree left, Btree right) { this.data = data; this.left = left; this.right = right; } @Override public void display(Consumer func) { this.left.display(func); func.accept(this.data); this.right.display(func); } @Override public Btree add(T data) { final int ans = this.data.compareTo(data); if (ans > 0) { return new Node(this.data, this.left.add(data), this.right); }else if (ans < 0) { return new Node(this.data, this.left, this.right.add(data)); }else { return this; } } @Override public Optional> find(T data) { final int ans = this.data.compareTo(data); if (ans > 0) { return this.left.find(data); }else if (ans < 0) { return this.right.find(data); }else { return Optional.of(this); } } @Override public boolean isEmpty() { return false; } private Btree joinBranches(Btree left, Btree right) { if (right.isEmpty()) { return left; }else { return new Node( ((Node)right).data, joinBranches(left, ((Node)right).left), ((Node)right).right ); } } @Override public Btree remove(T data) { final int ans = this.data.compareTo(data); if (ans > 0) { return new Node(this.data, this.left.remove(data), this.right); }else if (ans < 0) { return new Node(this.data, this.left, this.right.remove(data)); }else { if (this.left.isEmpty()) { return this.right; }else if (this.right.isEmpty()) { return this.left; }else { return joinBranches(this.left, this.right); } } } }