/** * Get the least common ancestor of this node and the specified other node. * * @param otherNode * @return */ public XholonTreeNode getLeastCommonAncestor(XholonTreeNode otherNode) { if (otherNode == null) { return this; } if (otherNode == this) { return this; } // if (isRootNode()) {return this;} // if (otherNode.isRootNode()) {return otherNode;} XholonTreeNode thisNode = this; // 2 nodes cannot have a common parent unless they are at the same level (depth), // so start by adjusting the path with the greatest depth int thisDepth = depth(); int otherDepth = otherNode.depth(); while (thisDepth > otherDepth) { thisNode = thisNode.getParentNode(); thisDepth--; } while (otherDepth > thisDepth) { otherNode = otherNode.getParentNode(); otherDepth--; } // now compare ancestors in lock-step while (!thisNode.equals(otherNode)) { thisNode = thisNode.getParentNode(); otherNode = otherNode.getParentNode(); } return thisNode; }
/* * @see org.primordion.xholon.base.IXholon#getRootNode() */ public XholonTreeNode getRootNode() { // get root node of this tree XholonTreeNode node = this; while (!node.isRootNode()) { node = node.getParentNode(); } return node; }
/* * @see org.primordion.xholon.base.IXholon#insertAfter(org.primordion.xholon.base.IXholon) */ public void insertAfter(XholonTreeNode newLeftSibling) { if (newLeftSibling.hasNextSibling()) { parent = newLeftSibling.getParentNode(); nextSibling = newLeftSibling.getNextSibling(); newLeftSibling.setNextSibling(this); } else { // last sibling setParentSiblingLinks(newLeftSibling); } }
/* * @see org.primordion.xholon.base.IXholon#insertBefore(org.primordion.xholon.base.IXholon) */ public void insertBefore(XholonTreeNode newNextSibling) { parent = newNextSibling.getParentNode(); if (parent.getFirstChild() == newNextSibling) { parent.setFirstChild(this); } else { XholonTreeNode lSibling = newNextSibling.getPreviousSibling(); lSibling.setNextSibling(this); } setNextSibling(newNextSibling); }
/* * @see org.primordion.xholon.base.IXholon#swapNode(org.primordion.xholon.base.IXholon) */ public void swapNode(XholonTreeNode otherNode) { XholonTreeNode thisParent = parent; XholonTreeNode otherParent = otherNode.getParentNode(); XholonTreeNode thisNextSibling = nextSibling; XholonTreeNode otherNextSibling = otherNode.getNextSibling(); if (thisParent != otherParent) { // no change if both have same parent removeChild(); otherNode.removeChild(); // insert this node if (otherNextSibling == null) { appendChild(otherParent); } else { insertBefore(otherNextSibling); } // insert other node if (thisNextSibling == null) { otherNode.appendChild(thisParent); } else { otherNode.insertBefore(thisNextSibling); } } }
/* * @see org.primordion.xholon.base.IXholon#setParentSiblingLinks(org.primordion.xholon.base.TreeNode) */ public void setParentSiblingLinks(XholonTreeNode previousSibling) { setParentNode(previousSibling.getParentNode()); // previousSibling already has parent previousSibling.setNextSibling(this); }