0

I wrote the following code but it doesn't work for nodes except the root node.

public Node deleteSubTree(Node root) {
    if(root == null) {
        return null;
    }
    root.left  =  deleteSubTree(root.left);
    root.right =  deleteSubTree(root.right);
            //System.out.print(" : deleting-"+root.data);
    root = null;
    return root;
}

I am passing the node to be deleted as the argument. Could you please tell what is wrong with this code?

  • 1
    You cannot modify the value of `root` in the caller, only the local copy. Also, to delete a subtree you must set the `left` or `right` reference in the subtree root's _parent_ to null, i.e. the reference in the root's parent that points to the root node of the subtree you want to delete. If all you have is a reference to the subtree root and no way to find the root's parent, you cannot delete the subtree. – Jim Garrison Apr 07 '18 at 05:15
  • I have the reference to the root's parent . So first i delete all the nodes and then set the root's parent (left/right) child to null. Is this what you are suggesting @JimGarrison ? – Harsh Palod Apr 07 '18 at 05:23
  • You should not need to do anything except set the parent's reference to the root (either `.left` or `.right`, whichever applies) to `null`. The rest will be cleaned up by GC. The entire now-unreachable subtree will be garbage collected. – Jim Garrison Apr 07 '18 at 05:25

0 Answers0