0

I've got objects organized in a tree (not binary one). Every node has collection of its Children and Parent property. It is all presented in a TreeView already. I would like to click on the leaf and delete it in such a way that leaf is removed, it goes up to the parent, if leaf was its only child and if parent's property X == null - remove it and again, go up. If not - stop. Could you, please, propose a solution for this problem? I think recursion could be useful here, but I don't know how to get it work properly.

Dawid
  • 763
  • 1
  • 8
  • 17

2 Answers2

1

This should have come as a comment, but still... I'm not familiar with TreeView you are using, but why don't you write something like:

    void removeNode(Node node) {
            if (node != null && node.getChildren().size() == 0) {
                    Node parent = node.getParent();
                    if (parent != null && parent.getChildren().size() == 1) {
                            parent.getChilder().clear();
                            removeNode(parent);
                    }
            }
    }

You call this methods whenever you 'click' (not sure how it looks in your program) a leaf node.

kt-9
  • 156
  • 4
0

It appears that I have found a solution. I thought I broke something with recursion before, but the problem turned out to be really tiny.

Here is my solution:

internal static void RemoveFromTree(ConfigurationItem item)
{
    NamedObject parent = item.Parent;

    if (parent is ConfigurationItem && parent.Children.Count == 1 && (parent as ConfigurationItem).ConfigId == null)
    {
        RemoveFromTree(parent as ConfigurationItem);
    }

    parent.Children.Remove(item);
    item.Parent = null;
}

NamedObject is a common ancestor of ConfigurationItem and ConfigurationRoot.

Dawid
  • 763
  • 1
  • 8
  • 17