I have a project in which I have to create a bst. So my problem is that I have to create a boolean method in which I check if the node is the Right/Left child of his Father.
public class TreeNode
{
private int data;
private TreeNode right;
private TreeNode left;
private TreeNode parent;
**assesor and mutator methods**
public TreeNode (int data)
{
this.data = data;
right = null;
left = null;
}
public boolean isRightChild (TreeNode parent)
{
if (parent.right.data == data)
{
return true;
}
return false;
}
public boolean isLeftChild (TreeNode parent)
{
if (parent.left.data == data)
{
return true;
}
return false;
}
}
and I call this method in another class with this...
node2.isRightChild(parent)
or
node2.isLeftChild(parent)
in compiler it shows me NullPointerException the insertion method (in another class) is...
public void insert(int data)
{
TreeNode element = new TreeNode (data);
if (node == null)
{
node = element;
return;
}
TreeNode node2 = node;
TreeNode parent = null;
while(true)
{
parent = node2;
if (data < node2.getData())
{
node2 = node2.getLeft();
if (node2 == null)
{
parent.setLeft(element);
return;
}
}else
{
node2 = node2.getRight();
if(node2 == null)
{
parent.setRight(element);
return;
}
}
}
}
UPDATE: My remove method is the following...
public boolean remove(int data)
{
TreeNode parent = node;
TreeNode node2 = node;
//searching through the nodes
while(node2.getData() != data)
{
parent = node2;
if(node2.getData() > data)
{
node2 = node2.getLeft();
}else
{
node2 = node2.getRight();
}
}
//empty node
if (node == null)
{
return false;
}
//leaf
if(node2.isLeaf(data))
{
if(node2 == node)
{
node = null;
}
if(node2.isRightChild(parent))
{
parent.setRight(null);
}else
{
parent.setLeft(null);
}
}
//node with 1 child
else if((node2.getLeft() == null))
{
if (node2 == node)
{
node = node2.getRight();
}else if(parent.isRightChild(node2))
{
parent.setRight(null);
}else
{
parent.setLeft(null);
}
}
else if((node2.getRight() == null))
{
if(node2 == node)
{
node = node2.getLeft();
}else if (node2.isLeftChild(parent))
{
parent.setLeft(null);
}else
{
parent.setLeft(null);
}
}
//node with 2 children
else if ((node2.getLeft() != null) && (node2.getRight() !=null))
{
TreeNode min = minFromRightSide(node2);
if(node2 == node)
{
node = min;
}else if(node2.isLeftChild(parent))
{
parent.setLeft(min);
}else
{
parent.setRight(min);
}
min.setLeft(node2.getLeft());
}
return true;
}
So finishing the problem is that with this remove method when node has one child instead of removing 1 node it removes this node AND his child... So when I try to remove the child later I obviously have NullPointerException