@Override
 public boolean offer(T data) {
   boolean offered = false;
   if (root == null) {
     root = new Node<T>(data);
     offered = true;
   } else if (data.compareTo(root.getValue()) == -1) {
     if (root.getLeft() == null) {
       root.setLeft(new Node<T>(data));
       offered = true;
     } else {
       offered = offer(data, root.getLeft(), root);
     }
   } else if (data.compareTo(root.getValue()) == 1) {
     if (root.getRight() == null) {
       root.setRight(new Node<T>(data));
       offered = true;
     } else {
       offered = offer(data, root.getRight(), root);
     }
   }
   balance(root, null);
   if (offered) {
     numValues++;
   }
   return offered;
 }
Example #2
0
  /* Given a binary tree, print its nodes in reverse level order */
  private void reverseLevelOrder(Node node, TraversalCallback callback) {
    Stack<Node> S = new Stack();
    Queue<Node> Q = new LinkedList();
    Q.add(node);

    // Do something like normal level order traversal order. Following are the
    // differences with normal level order traversal
    // 1) Instead of printing a node, we push the node to stack
    // 2) Right subtree is visited before left subtree
    while (Q.isEmpty() == false) {

      /* Dequeue node and make it root */
      node = Q.peek();
      Q.remove();
      S.push(node);

      /* Enqueue right child */
      if (node.getRight() != null) {
        Q.add(node.getRight()); // NOTE: RIGHT CHILD IS ENQUEUED BEFORE LEFT
      }
      /* Enqueue left child */
      if (node.getLeft() != null) {
        Q.add(node.getLeft());
      }
    }

    // Now pop all items from stack one by one and print them
    while (S.empty() == false) {
      node = S.peek();

      callback.execute(node);

      S.pop();
    }
  }
Example #3
0
 @Override
 public Zeepbel<Key> geefRechterBroerzeepbel() {
   if (getWortelNode().getParent() == null) {
     return null; // dan is dit de wortelzeepbel
   }
   Node<Key> zpblroot = getWortelNode();
   Zeepbel<Key> ouderzpbl = getOuderZeepbel();
   if (zpblroot.isRechterkind()) {
     Node<Key> node = zpblroot.getParent();
     while (node.isRechterkind()) {
       if (node.getParent() != null && node.getParent().getZeepbel() == ouderzpbl) {
         node = node.getParent();
       } else {
         return null; // geen linkerzeepbel, dit is de meest rechtse
       }
     }
     Node<Key> nodeP = node.getParent();
     return node.isRoot() || nodeP.getZeepbel() != ouderzpbl
         ? null
         : nodeP.getRight().inZelfdeZeepbelAls(nodeP)
             ? vindMinInZeepbelVanuit(nodeP.getRight()).getLeft().getZeepbel()
             : nodeP.getRight().getZeepbel();
   } else {
     // zpblroot is een linkerkind van zijn parent.
     assert (zpblroot.isLinkerkind());
     Node<Key> sibling = zpblroot.getSibling();
     assert (sibling != null); // zeepbel structuur, deze zeepbel is geen root
     if (sibling.getZeepbel() != getOuderZeepbel()) {
       assert (sibling.getZeepbel().getWortelNode() == sibling);
       return sibling.getZeepbel();
     } else {
       return vindMinInZeepbelVanuit(sibling).getLeft().getZeepbel();
     }
   }
 }
Example #4
0
  /**
   * Recursive method to add nodes to the binary tree.
   *
   * @param value Value being inserted
   * @param point point from which the tree is currently recursing down.
   */
  public void addNode(int value, Node point) {
    if (value < point.getValue()) { // check if has left child
      if (point.getLeft() == null) // if no, then add as left leaf to THIS node
      {
        point.setLeft(new Node(value, null, null, point));
        System.out.println("Added new node with value:" + value);
        //                                System.out.println("My Parent Node Is: " +
        // point.getValue()); //uncomment for debugging
        count++;
        return;
      } else { // if yes then call addNode at that child
        addNode(value, point.getLeft());
      }
    }

    if (value > point.getValue()) { // check if has right child
      if (point.getRight() == null) { // if no, then add as right leaf to THIS node
        point.setRight(new Node(value, null, null, point));
        System.out.println("Added new node with value:" + value);
        //                              System.out.println("My Parent Node Is: " +
        // point.getValue()); //uncomment for debugging
        count++;
        return;
      } else { // if yes, then call addNode at that child
        addNode(value, point.getRight());
      }
    }

    if (value == point.getValue()) {
      System.out.println("(!!) FAIL AT INSERTION: VALUE " + value + " ALREADY EXISTS IN TREE");
      return;
    }
  }
Example #5
0
  private void insert(Team team) {
    if (root == null) {
      root = new Node(team, 6);
      return;
    }

    Queue<Node> nodesToProcess = new LinkedList<>();
    nodesToProcess.add(root);

    while (true) {
      Node actualNode = nodesToProcess.poll();

      // Left child has precedence over right one
      if (actualNode.getLeft() == null) {
        actualNode.setLeft(new Node(team, actualNode.getLevel() - 1));
        return;
      }
      if (actualNode.getRight() == null) {
        actualNode.setRight(new Node(team, actualNode.getLevel() - 1));
        return;
      }

      // I have both children set, I will process them later if needed
      nodesToProcess.add(actualNode.getLeft());
      nodesToProcess.add(actualNode.getRight());
    }
  }
Example #6
0
 /**
  * generar codigo dot para el nodo, se usa para generar el arbol
  *
  * @param nodo nodo al que se le genera el codigo
  * @return cadena con el codigo dot
  */
 public static String toDot(Node nodo) {
   String left = "";
   String right = "";
   String ret = "";
   String cod = "";
   if (nodo.getHuffcode().equals("")) {
     cod = "Raรญz";
   } else {
     cod = nodo.getHuffcode();
   }
   if (nodo.getLeft() != null) {
     left = cod + " -> " + nodo.getLeft().getHuffcode() + "\n";
   }
   if (nodo.getRight() != null) {
     right = cod + " -> " + nodo.getRight().getHuffcode() + "[label=1]" + "\n";
   }
   ret =
       cod
           + " [shape=record, label=\"{{"
           + epsilon(nodo.getLetter())
           + "|"
           + nodo.getHowMany()
           + "}|"
           + empty(cod)
           + "}\"];\n"
           + left
           + right;
   if (nodo.getLeft() != null) {
     ret += toDot(nodo.getLeft());
   }
   if (nodo.getRight() != null) {
     ret += toDot(nodo.getRight());
   }
   return ret;
 }
  /**
   * Returns the node after the given one
   *
   * @param x node
   * @return next node
   * @throws HsqlException
   */
  Node next(Node x) throws HsqlException {

    if (x == null) {
      return null;
    }

    Node r = x.getRight();

    if (r != null) {
      x = r;

      Node l = x.getLeft();

      while (l != null) {
        x = l;
        l = x.getLeft();
      }

      return x;
    }

    Node ch = x;

    x = x.getParent();

    while (x != null && ch.equals(x.getRight())) {
      ch = x;
      x = x.getParent();
    }

    return x;
  }
Example #8
0
 /**
  * Zoekt binnen zeepbel en vanaf gegeven node (die erboven worden niet bekeken, ook al zitten ze
  * in dezelfde zeepbel).
  *
  * @param start : bevindt zich in deze zeepbel
  * @return :
  */
 private Node<Key> vindMaxInZeepbelVanuit(Node<Key> start) {
   assert (start.getZeepbel() == this);
   Node<Key> max = start;
   Zeepbel<Key> zpbl = start.getZeepbel();
   while (max.hasRight() && max.getRight().getZeepbel() == zpbl) {
     max = max.getRight();
   }
   return max;
 }
Example #9
0
 /**
  * Gets the right most child of a given node. Useful when deleting nodes from a tree.
  *
  * @param reference Node the search is stemming down from
  * @return Node Bottom right most node from a given branch
  */
 public Node getRightMostChild(Node reference) {
   if (reference.getRight() == null) // we are the right most node?
   {
     System.out.println(reference.getValue());
     return reference;
   } else { // not at the bottom
     return getRightMostChild(reference.getRight());
   }
 }
 private Node rotateRight(Node node) {
   Node temp = node;
   Node tempLeft = temp.getLeft();
   Node tempRight = temp.getRight();
   Node w = tempLeft.getLeft();
   Node x = tempLeft.getRight();
   temp = new Node(temp.getData(), x, tempRight);
   tempLeft = new Node(tempLeft.getData(), w, temp);
   return tempLeft;
 }
 private Node rotateLeft(Node node) {
   Node temp = node;
   Node nodeRight = temp.getRight();
   Node nodeLeft = temp.getLeft();
   Node w = nodeRight.getLeft();
   Node x = nodeRight.getRight();
   temp = new Node(temp.getData(), nodeLeft, w);
   nodeRight = new Node(nodeRight.getData(), temp, x);
   return nodeRight;
 }
  /**
   * Gets the largest item in the tree.
   *
   * @return Largest item in the tree
   */
  public Comparable getMax() {
    Node node = rootNode;
    if (node == null) return null;

    while (node.getRight() != null) node = node.getRight();

    splay(node.getValue());

    return node.getValue();
  }
Example #13
0
 /**
  * Procedimiente que aรฑade los nodos validos (con caracteres) a la lista
  *
  * @param list lista de nodos
  * @param nodo nodo a evaluar
  */
 public static void getNodeHuffcode(ArrayList<Node> list, Node nodo) {
   if (nodo.getLeft() != null) {
     list.add(nodo.getLeft());
     getNodeHuffcode(list, nodo.getLeft());
   }
   if (nodo.getRight() != null) {
     list.add(nodo.getRight());
     getNodeHuffcode(list, nodo.getRight());
   }
 }
Example #14
0
  public static void out(Tree t) {
    Queue<Node> q = new LinkedList<Node>();
    q.add(t.getRoot());

    while (!q.isEmpty()) {
      Node pop = q.remove();
      if (pop.getLeft() != null) q.add(pop.getLeft());
      if (pop.getRight() != null) q.add(pop.getRight());
      System.out.println(pop.getData());
    }
  }
 private Node<T> getRightMostParent(Node<T> current, Node<T> parent) {
   Node<T> node = null;
   if (current != null) {
     if (current.getRight() == null) {
       node = parent;
     } else {
       node = getRightMostParent(current.getRight(), current);
     }
   }
   return node;
 }
 private Node insert(Node node, int data) {
   if (node == null) {
     return new Node(data);
   }
   if (node.getData() < data) {
     node = new Node(node.getData(), node.getLeft(), insert(node.getRight(), data));
   } else if (node.getData() > data) {
     node = new Node(node.getData(), insert(node.getLeft(), data), node.getRight());
   }
   return checkingBalancing(node);
 }
Example #17
0
 /**
  * Pone el Codigo Huffman Correspondiente a cada nodo segun el codigo que llevava el padre
  *
  * @param nodo nodo a evaluar
  * @param huffcode codigo huffman del padre รณ "" si es el raiz
  * @return
  */
 public static Node evaluateNode(Node nodo, String huffcode) {
   nodo.setHuffcode(huffcode);
   if (nodo.getLeft() != null) {
     Node left = evaluateNode(nodo.getLeft(), nodo.getHuffcode() + "0");
     nodo.setLeft(left);
   }
   if (nodo.getRight() != null) {
     Node right = evaluateNode(nodo.getRight(), nodo.getHuffcode() + "1");
     nodo.setRight(right);
   }
   return nodo;
 }
 private int balanceNumber(Node node) {
   int lValue = depth(node.getLeft());
   int rValue = depth(node.getRight());
   if (lValue - rValue >= 2) return -1;
   else if (lValue - rValue <= -2) return 1;
   return 0;
 }
Example #19
0
 /**
  * Recursive method to print the list of ancestors of a given child
  *
  * @param search node being recursed down to initially
  * @param parent parent node currently being recursed at
  * @return boolean True when the child has been found, false if the method is still recursing to
  *     it.
  */
 public boolean ancestors(int search, Node parent) {
   if (parent != null) {
     if (search == parent.getValue()) // (1) Base Case: We are the child node in the search query
     {
       System.out.print(search + " ");
       return true;
     } else if (search > parent.getValue()) { // search value is greater than this one
       if (ancestors(search, parent.getRight())) {
         System.out.print(parent.getValue() + " ");
         return true;
       } else {
         return false;
       }
     } else if (search < parent.getValue()) { // search value is less than this one
       if (ancestors(search, parent.getLeft())) {
         System.out.print(parent.getValue() + " ");
         return true;
       } else {
         return false;
       }
     } else {
       return false;
     }
   } else { // if we made it this far then that node does not exist
     System.out.println("(!!) [" + search + "] NODE DOES NOT EXIST");
     return false;
   }
 }
 private void postorderPrinting(Node node) {
   if (node != null) {
     postorderPrinting(node.getLeft());
     postorderPrinting(node.getRight());
     System.out.print(node.getData() + " ");
   }
 }
Example #21
0
  @Override
  public boolean containsMoreThan1Key() {
    assert (root.getParent() == null || root.getParent().getZeepbel() != this);

    return (root.hasLeft() && root.getLeft().getZeepbel() == this)
        || (root.hasRight() && root.getRight().getZeepbel() == this);
  }
Example #22
0
 // this procedure selects a leaf and a word and then splits the leaf and
 // creates two new leaves
 private void improve() {
   Node bestLeaf = null; // getRandomLeaf();
   String bestWord = null; // Main.dict.getRandomWord();
   double bestIG = 0;
   Node currentLeaf;
   String currentWord;
   ArrayList<String> words;
   ArrayList<Message> msgs;
   for (int i = 0; i < leaves.size(); i++) {
     currentLeaf = leaves.get(i);
     msgs = currentLeaf.getMessages();
     for (int j = 0; j < msgs.size(); j++) {
       words = msgs.get(j).getWords();
       for (int k = 0; k < words.size(); k++) {
         currentWord = words.get(k);
         double currentIG = IG(currentWord, currentLeaf);
         if (currentIG >= bestIG) {
           bestIG = currentIG;
           bestWord = currentWord;
           bestLeaf = currentLeaf;
         }
       }
     }
   }
   //		System.out.println("Chose: "+ bestWord+" with IG: "+ bestIG);
   split(bestLeaf, bestWord);
   if (tenFirstWords.size() < 10) {
     tenFirstWords.add(bestWord);
   }
   // improvement
   leaves.remove(bestLeaf);
   leaves.add(bestLeaf.getLeft());
   leaves.add(bestLeaf.getRight());
 }
  MultiTypeNode copyFromFlatNode(Node node) {

    MultiTypeNode mNode = new MultiTypeNode();

    mNode.height = node.height;
    mNode.parent = node.parent;

    mNode.nTypeChanges = 0;
    mNode.changeTimes.addAll(new ArrayList<Double>());
    mNode.changeTypes.addAll(new ArrayList<Integer>());
    mNode.nodeType = 0;

    mNode.labelNr = node.labelNr;

    if (node.isLeaf()) {

      int type = (int) node.getMetaData("location");

      if (type != 0) {

        mNode.setNodeType(type);
        mNode.addChange(
            0,
            (node.getHeight()
                + (node.getParent().getHeight() - node.getHeight()) * Randomizer.nextDouble()));
      }

    } else {

      mNode.addChild(copyFromFlatNode(node.getLeft()));
      mNode.addChild(copyFromFlatNode(node.getRight()));
    }

    return mNode;
  }
Example #24
0
 public void PreOrder(Node localRoot) {
   if (localRoot != null) {
     System.out.println(localRoot.getItem());
     PreOrder(localRoot.getLeft());
     PreOrder(localRoot.getRight());
   }
 }
Example #25
0
  private Node rebalanceLeft(Node localRoot) {
    Node leftChild = localRoot.getLeft();
    if (leftChild.balance > Node.RIGHT_HEAVY) { // if it is a left-right Heavy tree
      Node leftRightChild = leftChild.getRight();
      if (leftRightChild.balance > Node.BALANCED) { // this if and else if are reversed for me
        localRoot.balance--;
        leftRightChild.balance--;
        leftChild.balance++;
      } else if (leftRightChild.balance < Node.BALANCED) {
        localRoot.balance--;
        leftRightChild.balance++;
        leftChild.balance++;
      } else {
        localRoot.balance = Node.BALANCED;
        leftRightChild.balance = Node.BALANCED;
        leftChild.balance = Node.BALANCED;
      }
      increase = false;
      decrease = true;

      rotateLeft(leftChild);
      return rebalanceLeft(rotateRight(localRoot)); // change this
    } else { // LEFT-LEFT
      increase = false;
      decrease = true;
    }
    // Now rotate the
    return rotateRight(localRoot);
  }
  /**
   * Removes the node with the value comp.
   *
   * @param comp Comparable being removed
   */
  public void remove(Comparable comp) {
    splay(comp);

    if (comp.compareTo(rootNode.getValue()) != 0) // Node not found
    return;

    if (rootNode.getLeft() == null) rootNode = rootNode.getRight();
    else {
      Node node = rootNode.getRight();
      rootNode = rootNode.getLeft();
      splay(comp);
      rootNode.setRight(node);
    }

    size--;
  }
  /**
   * Inserts a node into the SplayTree, then splays around that node.
   *
   * @param comp Comparable value of new node being added
   */
  public void insert(Comparable comp) {
    Node node = new Node(comp);
    if (rootNode == null && size == 0) {
      rootNode = node;
      return;
    }

    splay(comp);

    int temp = comp.compareTo(rootNode.getValue());
    if (temp == 0) // Double checks for duplicates
    return;

    if (temp < 0) {
      node.setLeft(rootNode.getLeft());
      node.setRight(rootNode);
      rootNode.setLeft(null);
    } else {
      node.setRight(rootNode.getRight());
      node.setLeft(rootNode);
      rootNode.setRight(null);
    }
    rootNode = node;
    size++;
  }
Example #28
0
  public static void main(String[] args) {
    Tree t = new Tree();
    Node root = new Node(1);
    root.setLeft(new Node(2));
    root.setRight(new Node(3));
    root.getLeft().setLeft(new Node(4));
    root.getRight().setLeft(new Node(5));
    root.getRight().setRight(new Node(6));
    root.getRight().getRight().setRight(new Node(7));

    t.setRoot(root);
    out(t);
    System.out.println();
    t.reverse(t.getRoot());
    out(t);
  }
 @Override
 public T poll() {
   Node<T> max = null;
   if (root != null) {
     if (root.getRight() != null) {
       Node<T> maxParent = getRightMostParent(root, null);
       max = maxParent.getRight();
       maxParent.setRight(max.getLeft());
     } else {
       max = root;
       root = root.getLeft();
     }
     numValues--;
   }
   return max.getValue();
 }
  /**
   * Return the first node equal to the rowdata object. Use visible columns only. The rowdata has
   * the same column mapping as this table.
   *
   * @param rowdata array containing table row data
   * @return matching node
   * @throws HsqlException
   */
  RowIterator findFirstRow(Session session, Object[] rowdata) throws HsqlException {

    Node x = getRoot(session);
    Node found = null;
    boolean unique = isUnique && !isNull(rowdata);

    while (x != null) {
      int c = compareRowNonUnique(session, rowdata, colIndex, x.getData());

      if (c == 0) {
        found = x;

        if (unique) {
          break;
        }

        x = x.getLeft();
      } else if (c < 0) {
        x = x.getLeft();
      } else {
        x = x.getRight();
      }
    }

    return found == null ? emptyIterator : new IndexRowIterator(session, this, found);
  }