/** * {@inheritDoc} */ @Override public void add(final TreeNode node) { if (node == this) { throw new IllegalArgumentException("Can't add a node to itself"); } if (this.isAncestor(node)) { throw new IllegalArgumentException("Can't add an ancestor as a child node"); } if (node.getParent() != null) { node.getParent().remove(node); } if (children == null) { children = new ArrayList<>(); } children.add(node); if (node instanceof AbstractTreeNode) { ((AbstractTreeNode) node).parent = this; } }
@Test public void testRemove() { TreeNode node = buildTestTree(); // Test removal of nodes which aren't children. node.remove(null); Assert.assertEquals("Incorrect tree after remove of null", "ABCDEFGH", treeToString(node)); node.remove(new TestNode()); Assert.assertEquals("Incorrect tree after remove of non-child", "ABCDEFGH", treeToString( node)); node.remove(getNode(node, "E")); Assert.assertEquals("Incorrect tree after remove of non-child", "ABCDEFGH", treeToString( node)); // Test individual node removal getNode(node, "D").remove(getNode(node, "G")); Assert.assertEquals("Incorrect tree after remove 'D'", "ABCDEFH", treeToString(node)); // Test branch removal. getNode(node, "B").remove(getNode(node, "F")); Assert.assertEquals("Incorrect tree after remove 'F'", "ABCDE", treeToString(node)); // Test removal at root. node.remove(getNode(node, "B")); Assert.assertEquals("Incorrect tree after remove 'B'", "ACD", treeToString(node)); // Test removal of all children node.remove(getNode(node, "C")); node.remove(getNode(node, "D")); Assert.assertEquals("Incorrect tree after remove of all children", "A", treeToString(node)); }