Exemplo n.º 1
0
  /*
  Method: parseInputLine - text parser
  Purpose: parse the line of text and returns a TreeNode
  Parameters:
      String line   the line of text being parsed
  Returns:
      Entry - the Object parsed from the text line
  */
  private TreeNode parseInputLine(String line) {
    if (line.equals("")) {
      // returns a null object if the line is empty
      // only null entry source in code
      return null;
    }

    // a new empty TreeNode object
    TreeNode returnNode = new TreeNode(ENTRY); // is an entry
    // Scanner to scan the line of text
    Scanner lineScanner = new Scanner(line);
    lineScanner.useDelimiter("/");

    // sets the entry's word
    returnNode.setMyString(lineScanner.next());

    while (lineScanner.hasNext()) {
      // the next word in the line
      String nextWord = lineScanner.next();
      // end of line and 'a//b/c' blank words
      if (!(nextWord == null) && !(nextWord.equals(""))) {
        // adds each word in alphabet order to the
        // synonym linkedList
        returnNode.addSynonymInOrder(nextWord);
        // might not have any synonyms
      }
    }
    // returns the finished entry object
    return returnNode;
  }
Exemplo n.º 2
0
  private void addCtxValue(TreeNode cycled, String[] pathParts, String value) {
    boolean pathCreated = false;
    for (int i = 2 + 1; i < pathParts.length; i++) {
      String encodedName = "/" + pathParts[i];
      TreeNode child = cycled.findChildByEncodedName(encodedName);
      if (child == null) {
        int type = ContextPathUtil.prefix2type(encodedName.substring(0, 4));
        cycled = cycled.addNode(type, encodedName);
        pathCreated = true;
      } else {
        cycled = child;
      }
    }

    if (pathCreated) {
      entryCounter++;
    }
    if (value != null) {
      cycled.addValue(value);
      modCount++;
    } else {
      // check whether the path was really created
      modCount = (pathCreated) ? modCount + 1 : modCount;
    }
  }
Exemplo n.º 3
0
    public void iterateThruContext(String ctxPath, TreeNodeHandler2 handler) {
      String[] path = ctxPath.split("/");
      final String filePath = "/" + path[1];
      int startWith = filePath.startsWith(ContextPath.FILE_CTX_PRX) ? 2 : 1;
      if (startWith == 1) {
        return;
      }

      TreeNode cycled = null;
      int cnt = 0;
      boolean ret = true;
      for (int i = 2; i < path.length && ret; i++) {
        String encodedName = "/" + path[i];
        if (i == 2) {
          cycled = findChildByEncodedName(encodedName, filePath);
        } else {
          cycled = cycled.findChildByEncodedName(encodedName);
        }

        if (cycled != null) {
          ret = handler.handleNode(cnt++, cycled);
        } else {
          // todo - ctx path looks not valid, handle it?
          return;
        }
      }
    }
Exemplo n.º 4
0
 public static boolean traverseDepth(final TreeNode node, final Traverse traverse) {
   if (!traverse.accept(node)) return false;
   final int childCount = node.getChildCount();
   for (int i = 0; i < childCount; i++)
     if (!traverseDepth(node.getChildAt(i), traverse)) return false;
   return true;
 }
Exemplo n.º 5
0
 // Method to calculate the above boundary queries
 // This method is called whenever a new node is inserted
 private void updateMinMax(TreeNode t, TreeNode newNode) {
   if (t == null && newNode == null) return;
   if (t.maxX.p.x() < newNode.p.x()) t.maxX = newNode;
   if (t.maxY.p.y() < newNode.p.y()) t.maxY = newNode;
   if (t.minX.p.x() > newNode.p.x()) t.minX = newNode;
   if (t.minY.p.y() > newNode.p.y()) t.minY = newNode;
 }
Exemplo n.º 6
0
  public boolean setContextPathAttr(String startCtxPath, String attrName, String value) {
    String[] path = startCtxPath.split("/");
    int startWith = ("/" + path[1]).startsWith(ContextPath.FILE_CTX_PRX) ? 2 : 1;

    TreeNode cycled = root;
    for (int i = startWith; i < path.length; i++) {
      String encodedName = "/" + path[i];
      cycled = cycled.findChildByEncodedName(encodedName);
      if (cycled == null) {
        return false;
      }
    }

    TreeNodeImpl nodeImpl = (TreeNodeImpl) cycled;
    int i = 0;
    for (; i < nodeImpl.extAttr.length; i++) {
      String _attrName = decodeAttrName(nodeImpl.extAttr[i]);
      if (_attrName.equals(attrName)) {
        // replace existing attribute with new one
        nodeImpl.extAttr[i] = encodeAttrValue(attrName, value);
        return true;
      }
    }
    nodeImpl.extAttr = increaseArrayByOne(nodeImpl.extAttr);
    // replace existing attribute with new one
    nodeImpl.extAttr[i] = encodeAttrValue(attrName, value);
    return true;
  }
Exemplo n.º 7
0
 /**
  * Recursive traverse of tree to determine selections A leaf is selected if rsm is selected.
  * Nonleaf nodes are selected if all children are selected.
  *
  * @param tn node in the tree for which to determine selection
  * @param nodeidx the ordinal postion in the segments array
  * @param gsm the graph segments selection model
  * @param rsm the table row selection model
  * @return true if given node tn is selected, else false
  */
 private boolean selTraverse(
     TreeNode tn, int[] nodeidx, ListSelectionModel gsm, ListSelectionModel rsm) {
   boolean selected = true;
   if (!tn.isLeaf()) {
     // A nonleaf node is selected if all its children are selected.
     for (int i = 0; i < tn.getChildCount(); i++) {
       TreeNode cn = tn.getChildAt(i);
       selected &= selTraverse(cn, nodeidx, gsm, rsm);
     }
   } else {
     if (tn instanceof RowCluster) {
       // get the row index of the leaf node
       int ri = ((RowCluster) tn).getIndex();
       // A leaf is selected if its row is selected in the row selection rsm.
       selected = rsm.isSelectedIndex(ri);
     }
   }
   // Get the offset into the segments array
   int idx = nodeidx[0] * segOffset;
   if (selected) {
     gsm.addSelectionInterval(idx, idx + (segOffset - 1));
   } else {
     gsm.removeSelectionInterval(idx, idx + (segOffset - 1));
   }
   // Increment the nodeidx in the tree
   nodeidx[0]++;
   return selected;
 }
Exemplo n.º 8
0
 public static ArrayList<TreeNode> childrenToArray(final TreeNode node) {
   final ArrayList<TreeNode> result = new ArrayList<TreeNode>();
   for (int i = 0; i < node.getChildCount(); i++) {
     result.add(node.getChildAt(i));
   }
   return result;
 }
Exemplo n.º 9
0
 private double evaluateNode(TreeNode root) // recursive
     {
   if (isOperator((String) root.getValue())) {
     return computeTerm(
         (String) root.getValue(), evaluateNode(root.getLeft()), evaluateNode(root.getRight()));
   } else return Double.parseDouble((String) root.getValue());
 }
Exemplo n.º 10
0
 /* Creates tree by mapping the array left to right, top to bottom. */
 public static TreeNode createTreeFromArray(int[] array) {
   if (array.length > 0) {
     TreeNode root = new TreeNode(array[0]);
     java.util.Queue<TreeNode> queue = new java.util.LinkedList<TreeNode>();
     queue.add(root);
     boolean done = false;
     int i = 1;
     while (!done) {
       TreeNode r = (TreeNode) queue.element();
       if (r.left == null) {
         r.left = new TreeNode(array[i]);
         i++;
         queue.add(r.left);
       } else if (r.right == null) {
         r.right = new TreeNode(array[i]);
         i++;
         queue.add(r.right);
       } else {
         queue.remove();
       }
       if (i == array.length) done = true;
     }
     return root;
   } else {
     return null;
   }
 }
Exemplo n.º 11
0
 /*10. 求二叉树的镜像
     递归解法:
     (1)如果二叉树为空,返回空
     (2)如果二叉树不为空,求左子树和右子树的镜像,然后交换左子树和右子树
 */
 public static TreeNode Mirror(TreeNode node) {
   if (node == null) {
     return null;
   }
   node.right = Mirror(node.left);
   node.left = Mirror(node.right);
   return node;
 }
Exemplo n.º 12
0
 public static boolean isAncestor(final TreeNode ancestor, final TreeNode node) {
   TreeNode parent = node;
   while (parent != null) {
     if (parent == ancestor) return true;
     parent = parent.getParent();
   }
   return false;
 }
Exemplo n.º 13
0
 public static TreeNode createBinaryTree(int[] values) {
   TreeNode root = new TreeNode();
   root.value = values[0];
   for (int i = 1; i < values.length; i++) {
     insert(root, values[i], root);
   }
   return root;
 }
Exemplo n.º 14
0
 public static void main(String[] args) {
   int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   TreeNode root = TreeNode.createMinimalBST(array);
   TreeNode n3 = root.find(1);
   TreeNode n7 = root.find(7);
   TreeNode ancestor = commonAncestor0(root, n3, n7);
   System.out.println(ancestor.data);
 }
Exemplo n.º 15
0
 public static TreeNode randomBST(int N, int min, int max) {
   int d = randomIntInRange(min, max);
   TreeNode root = new TreeNode(d);
   for (int i = 1; i < N; i++) {
     root.insertInOrder(randomIntInRange(min, max));
   }
   return root;
 }
Exemplo n.º 16
0
  public ContextItem[] findInRootContext(int[] types) {
    List<ContextItem> out = new ArrayList<ContextItem>();
    for (TreeNode n : root.findChildrenByTypes(types)) {
      // todo -- revise to replace using value directly with a TreeNode instance
      out.add(new ContextItemImpl(n.getPath(), n.getValue()));
    }

    return out.toArray(new ContextItem[out.size()]);
  }
Exemplo n.º 17
0
 private static void expand(JTree tree, TreePath path, int levels) {
   if (levels == 0) return;
   tree.expandPath(path);
   TreeNode node = (TreeNode) path.getLastPathComponent();
   Enumeration children = node.children();
   while (children.hasMoreElements()) {
     expand(tree, path.pathByAddingChild(children.nextElement()), levels - 1);
   }
 }
 private static void applyNode(TreeNode node, final CodeStyleSettings settings) {
   if (node instanceof MyTreeNode) {
     ((MyTreeNode) node).apply(settings);
   }
   for (int j = 0; j < node.getChildCount(); j++) {
     TreeNode child = node.getChildAt(j);
     applyNode(child, settings);
   }
 }
 private static void resetNode(TreeNode node, CodeStyleSettings settings) {
   if (node instanceof MyTreeNode) {
     ((MyTreeNode) node).reset(settings);
   }
   for (int j = 0; j < node.getChildCount(); j++) {
     TreeNode child = node.getChildAt(j);
     resetNode(child, settings);
   }
 }
Exemplo n.º 20
0
  @Override
  public void adoptElement(SceneElement elem) {
    if (!(elem instanceof NenyaImageSceneElement
        || elem instanceof NenyaTileSceneElement
        || elem instanceof NenyaComponentSceneElement)) {
      enableEditor(false);
      return;
    }

    DefaultComboBoxModel dcm = (DefaultComboBoxModel) itemList.getModel();

    // Important: Work on a copy, not on the original. Otherwise we mess up the undomanager
    sceneElement = elem.copy();

    if ((sceneElement instanceof NenyaImageSceneElement) && !locked) {
      dcm.removeAllElements();
      String[] tmp = ((NenyaImageSceneElement) sceneElement).getPath();
      dcm.addElement(tmp[tmp.length - 1]);
    }
    if ((sceneElement instanceof NenyaTileSceneElement) && !locked) {
      dcm.removeAllElements();
      dcm.addElement(((NenyaTileSceneElement) sceneElement).getTileName());
    }
    if ((sceneElement instanceof NenyaComponentSceneElement) && !locked) {
      dcm.removeAllElements();
      NenyaComponentItem[] ni = ((NenyaComponentSceneElement) sceneElement).getComponents();
      for (NenyaComponentItem element : ni) {
        dcm.addElement(element);
      }
    }

    try {
      ClassedItem[] cols = null;
      if (elem instanceof NenyaTileSceneElement)
        cols = ((NenyaTileSceneElement) elem).getColorList();
      if (elem instanceof NenyaImageSceneElement)
        cols = ((NenyaImageSceneElement) elem).getColorList();
      if (elem instanceof NenyaComponentSceneElement) {
        NenyaComponentItem nci = (NenyaComponentItem) dcm.getSelectedItem();
        cols = nci.getColorList();
      }
      Vector<TreePath> collect = new Vector<TreePath>();
      TreeNode root = (TreeNode) colors.getModel().getRoot();
      for (ClassedItem col : cols) {
        String[] tmp = {root.toString(), col.getClassName(), col.getItemName()};
        collect.add(TreeUtil.findPath(root, tmp));
      }
      TreePath[] path = collect.toArray(new TreePath[0]);
      colors.getSelectionModel().setSelectionPaths(path);
    } catch (Exception e) {
      // Either the tree is filtered away or the selected item is not colorized.
    }

    enableEditor(true);
    itemList.setEnabled(elem instanceof NenyaComponentSceneElement);
  }
Exemplo n.º 21
0
 /**
  * Return a count of this node and all its descendents.
  *
  * @param node A node in the Treemodel.
  * @return The number of nodes in this branch of the Treemodel.
  */
 private static int getNodeCount(TreeNode tn) {
   int nc = 1; // this node
   if (!tn.isLeaf()) {
     for (int i = 0; i < tn.getChildCount(); i++) {
       TreeNode cn = tn.getChildAt(i);
       nc += getNodeCount(cn);
     }
   }
   return nc;
 }
Exemplo n.º 22
0
 public void iterateTopNodes(String name, IndexEntriesWalkerInterruptable iproc) {
   List<TreeNodeImpl> list = root.childs.get(name.toLowerCase());
   if (list != null) {
     for (TreeNode n : list) {
       if (!iproc.process(n.getPath(), n.getValue())) {
         return;
       }
     }
   }
 }
Exemplo n.º 23
0
 public void iterateTopNodes(IndexEntriesWalkerInterruptable iproc) {
   // iterate thru children
   for (Map.Entry<String, List<TreeNodeImpl>> item : root.childs.entrySet()) {
     for (TreeNode n : item.getValue()) {
       if (!iproc.process(n.getPath(), n.getValue())) {
         return;
       }
     }
   }
 }
Exemplo n.º 24
0
  /**
   * @param xOrdered -- Points ordered on x
   * @param yOrdered -- Points ordered on y
   * @param cd -- cutting dimension
   * @return -- Root node This method builds a balanced tree(or sub-tree) in nlogn time. It does
   *     this by creating a root node based on the cutting dimension. It then splits up each list
   *     into sub-lists, for x-left, y-left, x-right, y-right.
   */
  private TreeNode buildBalanced(List<Point> xOrdered, List<Point> yOrdered, boolean cd) {
    TreeNode t = null;
    if (cd && !xOrdered.isEmpty()) {
      if (xOrdered.size() == 1) return new TreeNode(xOrdered.get(0));
      int median = xOrdered.size() / 2;
      t = new TreeNode(xOrdered.get(median));

      List<Point> xL = xOrdered.subList(0, median);
      List<Point> xR = xOrdered.subList(median + 1, xOrdered.size());
      List<Point> yL = new ArrayList<Point>(xOrdered.size());
      List<Point> yR = new ArrayList<Point>(xOrdered.size());
      for (int i = 0; i < yOrdered.size(); i++) {
        if (yOrdered.get(i).x() < t.p.x()) {
          yL.add(yOrdered.get(i));
        } else if (yOrdered.get(i).x() > t.p.x()) {
          yR.add(yOrdered.get(i));
        } else { // They must be equal, cut on y
          if (yOrdered.get(i).y() < t.p.y()) {
            yL.add(yOrdered.get(i));
          } else if (yOrdered.get(i).y() > t.p.y()) {
            yR.add(yOrdered.get(i));
          }
        }
      }
      t.left = buildBalanced(xL, yL, !cd);
      if (median >= 1) t.right = buildBalanced(xR, yR, !cd);
    } else if (!cd && !yOrdered.isEmpty()) {
      if (yOrdered.size() == 1) return new TreeNode(yOrdered.get(0));
      int median = yOrdered.size() / 2;
      t = new TreeNode(yOrdered.get(median));

      List<Point> xL = new ArrayList<Point>(yOrdered.size());
      List<Point> xR = new ArrayList<Point>(yOrdered.size());
      List<Point> yL = yOrdered.subList(0, median);
      List<Point> yR = yOrdered.subList(median + 1, xOrdered.size());

      for (int i = 0; i < xOrdered.size(); i++) {
        if (xOrdered.get(i).y() < t.p.y()) {
          xL.add(xOrdered.get(i));
        } else if (xOrdered.get(i).y() > t.p.y()) {
          xR.add(xOrdered.get(i));
        } else { // They must be equal, cut on x
          if (xOrdered.get(i).x() < t.p.x()) {
            xL.add(xOrdered.get(i));
          } else if (xOrdered.get(i).x() > t.p.x()) {
            xR.add(xOrdered.get(i));
          }
        }
      }
      t.left = buildBalanced(xL, yL, !cd);
      if (median >= 1) t.right = buildBalanced(xR, yR, !cd);
    }

    return t;
  }
Exemplo n.º 25
0
 /*
 Method: addEntryInOrder
 Purpose: adds an entry in order to the database
 Parameters:
     TreeNode newRntry - the entry being added
 Returns:
     boolean - did i do it?
 */
 public boolean addEntryInOrder(TreeNode newEntry) {
   // in scope, this. is an entry node adding a new syn to synTree
   if (newEntry == null || newEntry.getMyString().equals("")) {
     return false;
   }
   if (this.containsEntry(newEntry.getMyString())) {
     return false;
   }
   entryRoot = TreeNode.addTreeNodeInOrder(newEntry, entryRoot);
   return true;
 }
 private static boolean isModified(TreeNode node, final CodeStyleSettings settings) {
   if (node instanceof MyTreeNode) {
     if (((MyTreeNode) node).isModified(settings)) return true;
   }
   for (int j = 0; j < node.getChildCount(); j++) {
     TreeNode child = node.getChildAt(j);
     if (isModified(child, settings)) {
       return true;
     }
   }
   return false;
 }
Exemplo n.º 27
0
  /*
  Method: addSynonymFromMenu - database addition
  Purpose: adds a synonym to an existing entry
  Parameters:
      String wordToAddTo      the word to update
  Returns:
      none - the results are printed here
  */
  public void addSynonymFromMenu(String wordToAddTo) {
    if (wordToAddTo.equals("")) {
      // if the word is empty go back to caller
      System.out.println("\nPlease type a valid word\n");
      return;
    }

    // checks whether the word is in the database and gets it
    if (!this.containsEntry(wordToAddTo)) {
      // if the word isn't there, go back to caller
      System.out.println("Sorry, I could not find that word in the thesaurus\n");
      return;
    }
    TreeNode entryToModify = TreeNode.getNodeByString(wordToAddTo, entryRoot);

    // controls if the loop is repeated
    boolean repeatCheck = true;
    while (repeatCheck) {
      System.out.println("What synonym would you like " + "to add to the word: " + wordToAddTo);
      System.out.print(">> ");
      // Scanner to take user input
      Scanner inputScanner = new Scanner(System.in);
      // the synonym to be added
      // will accept spaces in words
      String userInput = inputScanner.nextLine();

      if (userInput.equals("")) {
        System.out.println("Sorry, I can't add nothing\n");
        // jump down to loop control
      } else {
        // checks to see if the entry already has that synonym

        if (entryToModify.containsSynonym(userInput))
          System.out.println(wordToAddTo + " already has that synonym\n");
        else {
          // adds the synonym to the entry
          entryToModify.addSynonymInOrder(userInput);
          System.out.println(userInput + " was added to the entry\n");
        }
      }

      // loop control menu
      System.out.println("\nWould you like to add another synonym?");
      System.out.print("type (yes/no) >>");
      // does the user want to add another entry?
      String userResponse = inputScanner.next();
      if (userResponse.equalsIgnoreCase("yes")) {
      } else {
        System.out.println("\nGoing back to the main menu\n");
        repeatCheck = false;
      }
    }
  }
Exemplo n.º 28
0
  /*
  Method: toString
  Purpose: sends the database to a string
  Parameters:
      TreeNode currentNode - the current node in the binary tree
  Returns:
  */
  private String toString(TreeNode currentNode) {
    String returnString = "";
    if (currentNode == null) {
      return returnString;
    }

    returnString += toString(currentNode.getLeftBranch());
    returnString += currentNode.toString() + "\r\n";
    returnString += toString(currentNode.getRightBranch());

    return returnString;
  }
Exemplo n.º 29
0
 /*
 Method: toFile
 Purpose: sends the database to a File
 Parameters:
     FileWriter fileWriter - the filewriter to pprint to file
     TreeNode current - current node bing printed
 Returns:
 */
 public void writeToFile(FileWriter fileWriter, TreeNode current) {
   try {
     if (current == null) {
       return;
     }
     fileWriter.write(current.toFile() + "\r\n");
     writeToFile(fileWriter, current.getLeftBranch());
     writeToFile(fileWriter, current.getRightBranch());
   } catch (IOException exception) {
     System.out.println("An error occurred in the file writing");
   }
 }
Exemplo n.º 30
0
 public TreeNode findChildByEncodedName(String encodedName) {
   String name = encodedName.substring(7, encodedName.length());
   List<TreeNodeImpl> lst = childs.get(name);
   if (lst != null) {
     for (TreeNode node : lst) {
       if (node.getName().equals(encodedName)) {
         return node;
       }
     }
   }
   return null;
 }