Search code examples
recursiontreegraph-algorithmtree-traversalrecurrence

How to remove path in tree starting from leaf?


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.


Solution

  • 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.