Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class BinarySearchTree<E> extends Product {
- protected Node<Product> root;
- public Node<Product> getRoot() {
- return root;
- }
- public void setRoot(Node<Product> root) {
- this.root = root;
- }
- public boolean isEmpty() {
- return this.root == null;
- }
- public BinarySearchTree() {
- this.root = null;
- }
- public BinarySearchTree(Product item) {
- this.root = new Node<Product>(item);
- }
- public BinarySearchTree(Product item, BinarySearchTree<E> leftTree, BinarySearchTree<E> rightTree) {
- this.root = new Node<Product>(item);
- if(leftTree != null) {
- this.root.Left = leftTree.root;
- }
- if(rightTree != null) {
- this.root.Right = rightTree.root;
- }
- }
- public void InOrden() {
- InOrden(this.root);
- }
- protected void InOrden(Node<Product> root) {
- if(root != null) {
- InOrden(root.Left);
- System.out.println(root.toString());
- InOrden(root.Right);
- }
- }
- public boolean Contains(int codigo) {
- return Contains(this.root, codigo);
- }
- private boolean Contains(Node<Product> root, Integer codigo) {
- if(root != null) {
- Integer codAux = root.item.getCodigo();
- if(codigo.compareTo(codAux) == 0) {
- return true;
- }
- else {
- if(codigo.compareTo(codAux) < 0) {
- return Contains(root.Left, codigo);
- }
- else {
- return Contains(root.Left, codigo);
- }
- }
- }
- return false;
- }
- public void Add(Product item) {
- if(this.isEmpty()) {
- this.setRoot(new Node<Product>(item));
- }
- else {
- Integer cod1 = item.getCodigo();
- Node<Product> temp = this.root, prev = null;
- while(temp != null) {
- prev = temp;
- Integer cod2 = temp.item.getCodigo();
- if (cod1.compareTo(cod2)<0) {
- temp = temp.Left;
- }
- else {
- temp = temp.Right;
- }
- }
- temp = new Node<Product>(item);
- Integer cod3 = prev.item.getCodigo();
- if (cod1.compareTo(cod3)<0) {
- prev.Left = temp;
- }else {
- prev.Right = temp;
- }
- }
- }
- public class Node<E> {
- public E item;
- public Node<E> Left;
- public Node<E> Right;
- public E getItem() {
- return item;
- }
- public void setItem(E item) {
- this.item = item;
- }
- public Node() {
- this.item = null;
- this.Left = this.Right = null;
- }
- public Node(E item) {
- this.item = item;
- this.Left = this.Right = null;
- }
- public Node(E item, Node Left, Node Right) {
- this.item = item;
- this.Left = Left;
- this.Right = Right;
- }
- public String toString() {
- return this.item.toString();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement