Question

private Node delete(Node n, int x)
{
    Node maxfromleft = null;
    if(n == null) return n;
    if (x < n.data)
    {
        n.left = delete(n.left, x);
    }
    else if(x > n.data)
    {
        n.right = delete(n.right, x);
    }
    else
    {
        if(n.right != null && n.left != null)
        {
                maxfromleft = max(n.left);
                delete(n.left, maxfromleft.data);
                n.data = maxfromleft.data;
        }
        else if(n.right == null)
        {
            n = n.left;
        }
        else if(n.left == null)
        {
            n = n.right;

        }
    }
    return n;
}

So I was working on binary tree implementation and I found very useful info here especially about remove method, and I made it so it works (well mostly). The issue is that when Root value is deleted it simply copies the value from the left to the root, so I am not sure about this and I hope some can aid me here.

Here is the max function used above:

  private Node max(Node n)
   {
      if(n==null)return null;
      if(n.right!=null) return max(n.right);
      return n;
   }
  public Node max()
  {
      return max(root);
  }
Was it helpful?

Solution

Try this fix:

maxfromleft = max(n.left);
n.left = delete(n.left, maxfromleft.data);
n.data = maxfromleft.data;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top