Filip_Markoski

[ADSx] - Merge Binary Search Trees

Jan 9th, 2018
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 20.54 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class MergeTrees {
  4.     public static void main(String args[]) {
  5.         Scanner scanner = new Scanner(System.in);
  6.  
  7.         BinarySearchTree<Integer> first = new BinarySearchTree<>();
  8.         BinarySearchTree<Integer> second = new BinarySearchTree<>();
  9.  
  10.         int numOfNodesFirst = Integer.parseInt(scanner.nextLine());
  11.         int numOfNodesSecond = Integer.parseInt(scanner.nextLine());
  12.         for (int i = 0; i < numOfNodesFirst; i++) {
  13.             int newNode = Integer.parseInt(scanner.nextLine());
  14.             first.insert(newNode);
  15.         }
  16.         for (int i = 0; i < numOfNodesSecond; i++) {
  17.             int newNode = Integer.parseInt(scanner.nextLine());
  18.             second.insert(newNode);
  19.         }
  20.  
  21.         Set<Integer> firstSet = first.storeInorder(first.getRoot());
  22.         Set<Integer> secondSet = second.storeInorder(second.getRoot());
  23.  
  24.         firstSet.addAll(secondSet);
  25.  
  26.         List<Integer> list = new ArrayList<>(firstSet);
  27.  
  28.         AVLTree<Integer> avlTree = new AVLTree<>();
  29.  
  30.         avlTree.listToTree(list);
  31.         avlTree.print();
  32.  
  33.     }
  34.  
  35.  
  36. }
  37.  
  38. /**
  39.  * Да се направи функција за спојување на две бинарни пребарувачки дрва во едно балансирано бинарно пребарувачко дрво AVL. Нека бројот на елементите на првото дрво е n, а на второто е m. Функцијата за спојување треба да биде со сложеност O(n+m).
  40.  * <p>
  41.  * Забелешка: Секоја друга имплементација која нема да соодветствува со бараната сложеност нема да се земе во предвид. Да се напише во коментар како е добиена бараната сложеност со вашата функција.
  42.  * <p>
  43.  * Влез: Во првиот ред се вчитува бројот на јазли кои ќе се внесуваат во првото дрво. Во вториот ред се вчитува бројот на јазли кои ќе се внесуваат во второто дрво. Понатака во секој ред одделно се дадени вредностите на јазлите од првото бинарно дрво, а после тоа од второто бинарно дрво.
  44.  * <p>
  45.  * Излез: Да се испечатат елементите во новодобиеното AVL дрво. (Користете ја методата print() од имплементацијата за AVL дрва)
  46.  * <p>
  47.  * Име на класа (Јава):MergeTrees
  48.  */
  49.  
  50.  
  51. class BinarySearchTree<E extends Comparable<E>> {
  52.  
  53.     /**
  54.      * The tree root.
  55.      */
  56.     private BNode<E> root;
  57.  
  58.     public BNode<E> getRoot() {
  59.         return root;
  60.     }
  61.  
  62.     /**
  63.      * Construct the tree.
  64.      */
  65.     public BinarySearchTree() {
  66.         root = null;
  67.     }
  68.  
  69.     /**
  70.      * Insert into the tree; duplicates are ignored.
  71.      *
  72.      * @param x the item to insert.
  73.      */
  74.     public void insert(E x) {
  75.         root = insert(x, root);
  76.     }
  77.  
  78.     /**
  79.      * Remove from the tree. Nothing is done if x is not found.
  80.      *
  81.      * @param x the item to remove.
  82.      */
  83.     public void remove(E x) {
  84.         root = remove(x, root);
  85.     }
  86.  
  87.     /**
  88.      * Find the smallest item in the tree.
  89.      *
  90.      * @return smallest item or null if empty.
  91.      */
  92.     public E findMin() {
  93.         return elementAt(findMin(root));
  94.     }
  95.  
  96.     /**
  97.      * Find the largest item in the tree.
  98.      *
  99.      * @return the largest item of null if empty.
  100.      */
  101.     public E findMax() {
  102.         return elementAt(findMax(root));
  103.     }
  104.  
  105.     /**
  106.      * Find an item in the tree.
  107.      *
  108.      * @param x the item to search for.
  109.      * @return the matching item or null if not found.
  110.      */
  111.     public BNode<E> find(E x) {
  112.         return find(x, root);
  113.     }
  114.  
  115.     /**
  116.      * Make the tree logically empty.
  117.      */
  118.     public void makeEmpty() {
  119.         root = null;
  120.     }
  121.  
  122.     /**
  123.      * Test if the tree is logically empty.
  124.      *
  125.      * @return true if empty, false otherwise.
  126.      */
  127.     public boolean isEmpty() {
  128.         return root == null;
  129.     }
  130.  
  131.     /**
  132.      * Print the tree contents in sorted order.
  133.      */
  134.     public void printTree() {
  135.         if (isEmpty()) {
  136.             System.out.println("Empty tree");
  137.         } else {
  138.             printTree(root);
  139.         }
  140.     }
  141.  
  142.     /**
  143.      * Internal method to get element field.
  144.      *
  145.      * @param t the node.
  146.      * @return the element field or null if t is null.
  147.      */
  148.     private E elementAt(BNode<E> t) {
  149.         if (t == null)
  150.             return null;
  151.         return t.info;
  152.     }
  153.  
  154.     /**
  155.      * Internal method to insert into a subtree.
  156.      *
  157.      * @param x the item to insert.
  158.      * @param t the node that roots the tree.
  159.      * @return the new root.
  160.      */
  161.     private BNode<E> insert(E x, BNode<E> t) {
  162.         if (t == null) {
  163.             t = new BNode<E>(x, null, null);
  164.         } else if (x.compareTo(t.info) < 0) {
  165.             t.left = insert(x, t.left);
  166.         } else if (x.compareTo(t.info) > 0) {
  167.             t.right = insert(x, t.right);
  168.         } else ;  // Duplicate; do nothing
  169.         return t;
  170.     }
  171.  
  172.     /**
  173.      * Internal method to remove from a subtree.
  174.      *
  175.      * @param x the item to remove.
  176.      * @param t the node that roots the tree.
  177.      * @return the new root.
  178.      */
  179.     private BNode<E> remove(Comparable x, BNode<E> t) {
  180.         if (t == null)
  181.             return t;   // Item not found; do nothing
  182.  
  183.         if (x.compareTo(t.info) < 0) {
  184.             t.left = remove(x, t.left);
  185.         } else if (x.compareTo(t.info) > 0) {
  186.             t.right = remove(x, t.right);
  187.         } else if (t.left != null && t.right != null) { // Two children
  188.             t.info = findMin(t.right).info;
  189.             t.right = remove(t.info, t.right);
  190.         } else {
  191.             if (t.left != null)
  192.                 return t.left;
  193.             else
  194.                 return t.right;
  195.         }
  196.         return t;
  197.     }
  198.  
  199.     /**
  200.      * Internal method to find the smallest item in a subtree.
  201.      *
  202.      * @param t the node that roots the tree.
  203.      * @return node containing the smallest item.
  204.      */
  205.     private BNode<E> findMin(BNode<E> t) {
  206.         if (t == null) {
  207.             return null;
  208.         } else if (t.left == null) {
  209.             return t;
  210.         }
  211.         return findMin(t.left);
  212.     }
  213.  
  214.     /**
  215.      * Internal method to find the largest item in a subtree.
  216.      *
  217.      * @param t the node that roots the tree.
  218.      * @return node containing the largest item.
  219.      */
  220.     private BNode<E> findMax(BNode<E> t) {
  221.         if (t == null) {
  222.             return null;
  223.         } else if (t.right == null) {
  224.             return t;
  225.         }
  226.         return findMax(t.right);
  227.     }
  228.  
  229.     /**
  230.      * Internal method to find an item in a subtree.
  231.      *
  232.      * @param x is item to search for.
  233.      * @param t the node that roots the tree.
  234.      * @return node containing the matched item.
  235.      */
  236.     private BNode<E> find(E x, BNode<E> t) {
  237.         if (t == null)
  238.             return null;
  239.  
  240.         if (x.compareTo(t.info) < 0) {
  241.             return find(x, t.left);
  242.         } else if (x.compareTo(t.info) > 0) {
  243.             return find(x, t.right);
  244.         } else {
  245.             return t;    // Match
  246.         }
  247.     }
  248.  
  249.     /**
  250.      * Internal method to print a subtree in sorted order.
  251.      *
  252.      * @param t the node that roots the tree.
  253.      */
  254.     private void printTree(BNode<E> t) {
  255.         if (t != null) {
  256.             printTree(t.left);
  257.             System.out.println(t.info);
  258.             printTree(t.right);
  259.         }
  260.     }
  261.  
  262.     public Set<E> storeInorderUtil(BNode<E> node, Set<E> list) {
  263.         if (node == null) return list;
  264.         storeInorderUtil(node.left, list);
  265.         list.add(node.info);
  266.         storeInorderUtil(node.right, list);
  267.         return list;
  268.     }
  269.  
  270.     public Set<E> storeInorder(BNode<E> node) {
  271.         Set<E> list1 = new TreeSet<>();
  272.         Set<E> result = storeInorderUtil(node, list1);
  273.         return result;
  274.     }
  275. }
  276.  
  277. class AVLTree<E extends Comparable<E>> {
  278.  
  279.     public AVLNode<E> getRoot() {
  280.         return root;
  281.     }
  282.  
  283.     public AVLNode<E> ListToAVLTree(List<E> list, int start, int end, int depth) {
  284.         if (start > end) return null;
  285.  
  286.         int mid = (start + end) / 2;
  287.         AVLNode<E> node = new AVLNode<E>(list.get(mid));
  288.         //int height = myHeight(node);
  289.         node.setHeight(depth);
  290.  
  291.         node.left = ListToAVLTree(list, start, mid - 1, depth + 1);
  292.         node.right = ListToAVLTree(list, mid + 1, end, depth + 1);
  293.         return node;
  294.     }
  295.  
  296.     public void listToTree(List<E> list) {
  297.         AVLNode<E> integerBNode = ListToAVLTree(list, 0, list.size() - 1, 0);
  298.         this.setRoot(integerBNode);
  299.     }
  300.  
  301.     public int myHeight(AVLNode<E> node) {
  302.         if (node == null) return 0;
  303.         return 1 +Math.max(myHeight(node.left), myHeight(node.right));
  304.     }
  305.  
  306.     /**
  307.      * The tree root.
  308.      */
  309.     private AVLNode<E> root;
  310.  
  311.     /**
  312.      * Construct the tree.
  313.      */
  314.     public AVLTree() {
  315.         root = null;
  316.     }
  317.  
  318.     public void setRoot(AVLNode<E> root) {
  319.         this.root = root;
  320.     }
  321.  
  322.     /**
  323.      * Insert into the tree; duplicates are ignored.
  324.      *
  325.      * @param x the item to insert.
  326.      */
  327.     public void insert(E x) {
  328.         root = insert(x, root);
  329.     }
  330.  
  331.     /**
  332.      * Remove from the tree. Nothing is done if x is not found.
  333.      *
  334.      * @param x the item to remove.
  335.      */
  336.     public void remove(E x) {
  337.         root = remove(x, root);
  338.     }
  339.  
  340.     // key - x
  341.     // root - t
  342.  
  343.     private AVLNode<E> remove(E x, AVLNode<E> t) {
  344.  
  345.         // STEP 1: PERFORM STANDARD BST DELETE
  346.         if (t == null)
  347.             return t;
  348.  
  349.         // If the key to be deleted is smaller than the root's key,
  350.         // then it lies in left subtree
  351.         if (x.compareTo(t.info) < 0)
  352.             t.left = remove(x, t.left);
  353.         else if (x.compareTo(t.info) > 0)
  354.             t.right = remove(x, t.right);
  355.         else {
  356.             // if key is same as root's key, then This is the node
  357.             // to be deleted
  358.             AVLNode<E> tmp;
  359.  
  360.             // node with only one child or no child
  361.             if ((t.left == null) || (t.right == null)) {
  362.  
  363.                 if (t.left != null)
  364.                     tmp = t.left;
  365.                 else
  366.                     tmp = t.right;
  367.  
  368.                 // no child case
  369.                 if (tmp == null) {
  370.                     tmp = t;
  371.                     t = null;
  372.                 } else {
  373.                     // one child case
  374.                     t = tmp;
  375.                 }
  376.             } else {
  377.                 // node with two children: Get the inorder successor (smallest
  378.                 // in the right subtree)
  379.                 tmp = findMin(t.right);
  380.                 // Copy the inorder successor's data to this node
  381.                 t.info = tmp.info;
  382.                 // Delete the inorder successor
  383.                 t.right = remove(tmp.info, t.right);
  384.             }
  385.  
  386.         }
  387.  
  388.         // If the tree had only one node then return
  389.         if (t == null)
  390.             return t;
  391.  
  392.         // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE
  393.         t.height = max(height(t.left), height(t.right)) + 1;
  394.  
  395.         // STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether
  396.         //  this node became unbalanced)
  397.         int balance = getBalance(t);
  398.  
  399.         // If this node becomes unbalanced, then there are 4 cases
  400.  
  401.         // Left Left Case
  402.         if ((balance > 1) && (getBalance(t.left) >= 0))
  403.             return rotateWithLeftChild(t);
  404.  
  405.         // Left Right Case
  406.         if ((balance > 1) && (getBalance(t.left) < 0))
  407.             return doubleWithLeftChild(t);
  408.  
  409.         // Right Right Case
  410.         if ((balance < -1) && (getBalance(t.right) <= 0))
  411.             return rotateWithRightChild(t);
  412.  
  413.         // Right Left Case
  414.         if ((balance < -1) && (getBalance(t.right) > 0))
  415.             return doubleWithRightChild(t);
  416.  
  417.         return t;
  418.     }
  419.  
  420.     // Get Balance factor of node N
  421.     int getBalance(AVLNode<E> n) {
  422.         if (n == null)
  423.             return 0;
  424.         return height(n.left) - height(n.right);
  425.     }
  426.  
  427.     /**
  428.      * Find the smallest item in the tree.
  429.      *
  430.      * @return smallest item or null if empty.
  431.      */
  432.     public E findMin() {
  433.         return elementAt(findMin(root));
  434.     }
  435.  
  436.     /**
  437.      * Find the largest item in the tree.
  438.      *
  439.      * @return the largest item of null if empty.
  440.      */
  441.     public E findMax() {
  442.         return elementAt(findMax(root));
  443.     }
  444.  
  445.     /**
  446.      * Find an item in the tree.
  447.      *
  448.      * @param x the item to search for.
  449.      * @return the matching item or null if not found.
  450.      */
  451.     public E find(E x) {
  452.         return elementAt(find(x, root));
  453.     }
  454.  
  455.     /**
  456.      * Make the tree logically empty.
  457.      */
  458.     public void makeEmpty() {
  459.         root = null;
  460.     }
  461.  
  462.     /**
  463.      * Test if the tree is logically empty.
  464.      *
  465.      * @return true if empty, false otherwise.
  466.      */
  467.     public boolean isEmpty() {
  468.         return root == null;
  469.     }
  470.  
  471.     /**
  472.      * Print the tree contents in sorted order.
  473.      */
  474.     public void printTree() {
  475.         if (isEmpty()) {
  476.             System.out.println("Empty tree");
  477.         } else {
  478.             printTree(root);
  479.         }
  480.     }
  481.  
  482.     /**
  483.      * Internal method to get element field.
  484.      *
  485.      * @param t the node.
  486.      * @return the element field or null if t is null.
  487.      */
  488.     private E elementAt(AVLNode<E> t) {
  489.         if (t == null)
  490.             return null;
  491.         else
  492.             return t.info;
  493.     }
  494.  
  495.     /**
  496.      * Internal method to insert into a subtree.
  497.      *
  498.      * @param x the item to insert.
  499.      * @param t the node that roots the tree.
  500.      * @return the new root.
  501.      */
  502.     private AVLNode<E> insert(E x, AVLNode<E> t) {
  503.         if (t == null) {
  504.             t = new AVLNode<E>(x, null, null);
  505.         } else if (x.compareTo(t.info) < 0) {
  506.             t.left = insert(x, t.left);
  507.             if (height(t.left) - height(t.right) == 2) {
  508.                 if (x.compareTo(t.left.info) < 0) {
  509.                     t = rotateWithLeftChild(t);
  510.                 } else {
  511.                     t = doubleWithLeftChild(t);
  512.                 }
  513.             }
  514.         } else if (x.compareTo(t.info) > 0) {
  515.             t.right = insert(x, t.right);
  516.             if (height(t.right) - height(t.left) == 2) {
  517.                 if (x.compareTo(t.right.info) > 0) {
  518.                     t = rotateWithRightChild(t);
  519.                 } else {
  520.                     t = doubleWithRightChild(t);
  521.                 }
  522.             }
  523.         } else
  524.             ;  // Duplicate; do nothing
  525.         t.height = max(height(t.left), height(t.right)) + 1;
  526.         return t;
  527.     }
  528.  
  529.     /**
  530.      * Internal method to find the smallest item in a subtree.
  531.      *
  532.      * @param t the node that roots the tree.
  533.      * @return node containing the smallest item.
  534.      */
  535.     private AVLNode<E> findMin(AVLNode<E> t) {
  536.         if (t == null) {
  537.             return t;
  538.         }
  539.  
  540.         while (t.left != null) {
  541.             t = t.left;
  542.         }
  543.         return t;
  544.     }
  545.  
  546.     /**
  547.      * Internal method to find the largest item in a subtree.
  548.      *
  549.      * @param t the node that roots the tree.
  550.      * @return node containing the largest item.
  551.      */
  552.     private AVLNode<E> findMax(AVLNode<E> t) {
  553.         if (t == null) {
  554.             return t;
  555.         }
  556.  
  557.         while (t.right != null) {
  558.             t = t.right;
  559.         }
  560.         return t;
  561.     }
  562.  
  563.     /**
  564.      * Internal method to find an item in a subtree.
  565.      *
  566.      * @param x is item to search for.
  567.      * @param t the node that roots the tree.
  568.      * @return node containing the matched item.
  569.      */
  570.     private AVLNode<E> find(E x, AVLNode<E> t) {
  571.         while (t != null) {
  572.             if (x.compareTo(t.info) < 0) {
  573.                 t = t.left;
  574.             } else if (x.compareTo(t.info) > 0) {
  575.                 t = t.right;
  576.             } else {
  577.                 return t;    // Match
  578.             }
  579.         }
  580.         return null;   // No match
  581.     }
  582.  
  583.     /**
  584.      * Internal method to print a subtree in sorted order.
  585.      *
  586.      * @param t the node that roots the tree.
  587.      */
  588.     private void printTree(AVLNode<E> t) {
  589.         if (t != null) {
  590.             printTree(t.left);
  591.             System.out.println(t.info);
  592.             printTree(t.right);
  593.         }
  594.     }
  595.  
  596.     /**
  597.      * Return the height of node t, or -1, if null.
  598.      */
  599.     private int height(AVLNode<E> t) {
  600.         if (t == null)
  601.             return -1;
  602.         else
  603.             return t.height;
  604.     }
  605.  
  606.     /**
  607.      * Return maximum of lhs and rhs.
  608.      */
  609.     private int max(int lhs, int rhs) {
  610.         if (lhs > rhs)
  611.             return lhs;
  612.         else
  613.             return rhs;
  614.     }
  615.  
  616.     /**
  617.      * Rotate binary tree node with left child.
  618.      * For AVL trees, this is a single rotation for case 1.
  619.      * Update heights, then return new root.
  620.      */
  621.     private AVLNode<E> rotateWithLeftChild(AVLNode<E> k2) {
  622.         AVLNode<E> k1 = k2.left;
  623.         k2.left = k1.right;
  624.         k1.right = k2;
  625.         k2.height = max(height(k2.left), height(k2.right)) + 1;
  626.         k1.height = max(height(k1.left), k2.height) + 1;
  627.         return k1;
  628.     }
  629.  
  630.     /**
  631.      * Rotate binary tree node with right child.
  632.      * For AVL trees, this is a single rotation for case 4.
  633.      * Update heights, then return new root.
  634.      */
  635.     private AVLNode<E> rotateWithRightChild(AVLNode<E> k1) {
  636.         AVLNode<E> k2 = k1.right;
  637.         k1.right = k2.left;
  638.         k2.left = k1;
  639.         k1.height = max(height(k1.left), height(k1.right)) + 1;
  640.         k2.height = max(height(k2.right), k1.height) + 1;
  641.         return k2;
  642.     }
  643.  
  644.     /**
  645.      * Double rotate binary tree node: first left child
  646.      * with its right child; then node k3 with new left child.
  647.      * For AVL trees, this is a double rotation for case 2.
  648.      * Update heights, then return new root.
  649.      */
  650.     private AVLNode<E> doubleWithLeftChild(AVLNode<E> k3) {
  651.         k3.left = rotateWithRightChild(k3.left);
  652.         return rotateWithLeftChild(k3);
  653.     }
  654.  
  655.     /**
  656.      * Double rotate binary tree node: first right child
  657.      * with its left child; then node k1 with new right child.
  658.      * For AVL trees, this is a double rotation for case 3.
  659.      * Update heights, then return new root.
  660.      */
  661.     private AVLNode<E> doubleWithRightChild(AVLNode<E> k1) {
  662.         k1.right = rotateWithLeftChild(k1.right);
  663.         return rotateWithRightChild(k1);
  664.     }
  665.  
  666.  
  667.     ////////////Tree print ////////////
  668.     public void print() {
  669.         // Print a textual representation of this AVL-tree.
  670.         printSubtree(root, "", null);
  671.     }
  672.  
  673.     private void printSubtree(AVLNode<E> tmp, String indent, AVLNode<E> parent) {
  674.         // Print a textual representation of the subtree of this AVL-tree whose
  675.         // topmost AVLNode is top, indented by the string of spaces indent.
  676.         if (tmp != null) {
  677.             //System.out.println(indent + "o-->");
  678.             String childIndent = indent + "    ";
  679.             printSubtree(tmp.right, childIndent, tmp);
  680.  
  681.             int total = this.myHeight(root);
  682.             int height = Math.abs(total - tmp.height - 1);
  683.             System.out.println(childIndent + tmp.info + " (" + height + ")");
  684.             //+ (parent == null ? "" : " parent " + parent.info.toString()));
  685.             printSubtree(tmp.left, childIndent, tmp);
  686.         }
  687.     }
  688. }
  689.  
  690. class BNode<E extends Comparable<E>> {
  691.  
  692.     public E info;
  693.     public BNode<E> left;
  694.     public BNode<E> right;
  695.  
  696.     public BNode(E info) {
  697.         this.info = info;
  698.         left = null;
  699.         right = null;
  700.     }
  701.  
  702.     public BNode(E info, BNode<E> left, BNode<E> right) {
  703.         this.info = info;
  704.         this.left = left;
  705.         this.right = right;
  706.     }
  707.  
  708. }
  709.  
  710. class AVLNode<E extends Comparable<E>> {
  711.  
  712.     public E info;
  713.     public AVLNode<E> left;
  714.     public AVLNode<E> right;
  715.     public int height;
  716.  
  717.     // Constructors
  718.     AVLNode(E theElement) {
  719.         this(theElement, null, null);
  720.     }
  721.  
  722.     AVLNode(E info, AVLNode<E> left, AVLNode<E> right) {
  723.         this.info = info;
  724.         this.left = left;
  725.         this.right = right;
  726.         height = 0;
  727.     }
  728.  
  729.     public void setHeight(int height) {
  730.         this.height = height;
  731.     }
  732. }
Advertisement
Add Comment
Please, Sign In to add comment