/** * Clones the node * * @see #cloneNode() */ public Object clone() { return cloneNode(); }
/** * Add subtree to existing tree, recursive iteration over the subtree to add * * @param tree the target tree * @param parent the parent node * @param newNode the current node to be added to the parent * @return node added node */ private TreeNode addSubtree(Tree tree, TreeNode parent, TreeNode newNode) { TreeNode nn = newNode.cloneNode(); nn.setIndex(-1); tree.addVertex(nn); tree.addEdge(parent, nn); for (TreeNode child : newNode.children()) { addSubtree(tree, nn, child); } return nn; }
@SuppressWarnings("unchecked") private void hangIn(TreeNode newParent, TreeNode oldParent, Tree tree) { for (TreeNode n : oldParent.children()) { TreeNode newNode = n.cloneNode(); newNode.setIndex(-1); tree.addVertex(newNode); Edge edge = tree.addEdge(newParent, newNode); edge.setWeight(n.getDistanceToParent()); hangIn(newNode, n, tree); } }
/** * Create a new {@link Tree} that represents the subtree of this tree rooted at the given * node. The returned tree is a new tree that contains clones of the {@link TreeNode}s of this tree. * The node copies are created using {@link TreeNode#cloneNode()} and are * new instances, so you will not have object equality ( n != n.cloneNode() ). Node equality using * {@link TreeNode#equals(Object)} will work at least for labeled nodes (because the labels are compared), but * for performance reasons we do not do deep checks. * <p> * If this tree does not contain the given node, null is returned. * * @param n the root node of the subtree * @return subtree rooted at the given node or null */ public Tree getSubtree(TreeNode n) { if (n == null) throw new NullPointerException(); if (nodes.get(n.getIndex()) != n) { return null; } Tree r = new Tree(); r.setName(getName()); TreeNode root = n.cloneNode(); root.setIndex(-1); // reset index r.addVertex(root); r.setRoot(root); hangIn(root, n, r); return r; }