davegimo

es2

Aug 19th, 2023
1,124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. class Node {
  2.  
  3.     public int value;
  4.     public String q;
  5.     public Node left;
  6.     public Node right;
  7.  
  8.     public Node(int value, String q) {
  9.         this.value = value;
  10.         this.q = q;
  11.         right = null;
  12.         left = null;
  13.     }
  14. }
  15.  
  16.  
  17. public class BinaryTree {
  18.  
  19.     public Node root;
  20.  
  21.     public Node addRecursive(Node current, int value, String q) {
  22.         if (current == null) {
  23.             return new Node(value,q);
  24.         }
  25.    
  26.         if (value < current.value) {
  27.             current.left = addRecursive(current.left, value, q);
  28.         } else if (value >= current.value) {
  29.             current.right = addRecursive(current.right, value, q);
  30.         } else {
  31.             // value already exists
  32.             return current;
  33.         }
  34.    
  35.         return current;
  36.     }
  37.  
  38.     public void add(int value, String q) {
  39.         root = addRecursive(root, value, q);
  40.     }
  41.  
  42.    
  43.  
  44.     public static void main(String[] args) {
  45.         BinaryTree bt = new BinaryTree();
  46.    
  47.         bt.add(170, "albergo");
  48.         bt.add(130, "campionato");
  49.         bt.add(90, "fiume");
  50.         bt.add(20, "patate");
  51.         bt.add(8, "frutta");
  52.         bt.add(222, "eletto");
  53.         bt.add(51, "sentieri");
  54.  
  55.         System.out.println(bt.root.left.left.value);
  56.         System.out.println(bt.root.left.left.q);
  57.        
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment