Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package myBtree;
- import java.util.function.Consumer;
- import java.util.Optional;
- final public class Node<T extends Comparable<T>> extends Btree<T> {
- private final T data;
- private final Btree<T> left;
- private final Btree<T> right;
- protected Node(T data, Btree<T> left, Btree<T> right) {
- this.data = data;
- this.left = left;
- this.right = right;
- }
- @Override
- public void display(Consumer<T> func) {
- this.left.display(func);
- func.accept(this.data);
- this.right.display(func);
- }
- @Override
- public Btree<T> add(T data) {
- final int ans = this.data.compareTo(data);
- if (ans > 0) {
- return new Node<T>(this.data, this.left.add(data), this.right);
- }else if (ans < 0) {
- return new Node<T>(this.data, this.left, this.right.add(data));
- }else {
- return this;
- }
- }
- @Override
- public Optional<Btree<T>> 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<T> joinBranches(Btree<T> left, Btree<T> right) {
- if (right.isEmpty()) {
- return left;
- }else {
- return
- new Node<T>(
- ((Node<T>)right).data,
- joinBranches(left, ((Node<T>)right).left),
- ((Node<T>)right).right
- );
- }
- }
- @Override
- public Btree<T> remove(T data) {
- final int ans = this.data.compareTo(data);
- if (ans > 0) {
- return new Node<T>(this.data, this.left.remove(data), this.right);
- }else if (ans < 0) {
- return new Node<T>(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);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement