I could not find people to explain me this java code properly so finally I am posting this question.please explain the process how that particular statement is affecting the tree.the problems are stated in the comments.I have problems in the BST class.
import java.util.Scanner;
class BSTNode
{
BSTNode left, right;
int data;
public BSTNode()
{
left = null;
right = null;
data = 0;
}
public BSTNode(int n)
{
left = null;
right = null;
data = n;
}
public void setLeft(BSTNode n)
{
left = n;
}
public void setRight(BSTNode n)
{
right = n;
}
public BSTNode getLeft()
{
return left;
}
public BSTNode getRight()
{
return right;
}
public void setData(int d)
{
data = d;
}
public int getData()
{
return data;
}
}
class BST
{
private BSTNode root;
public BST()
{
root = null;
}
public boolean isEmpty()
{
return root == null;
}
Why is the insert function written like root=insert(.....
. Is it returning root = actual root element each time?
public void insert(int data)
{
root = insert(root, data);
}
I understand how the inserting process is going on but what is the insert function returning? I know that it returns some node but how the is the process going on during iteration?
private BSTNode insert(BSTNode node, int data)
{
if (node == null)
node = new BSTNode(data);
else
{
if (data <= node.getData())
node.left = insert(node.left, data);
else
node.right = insert(node.right, data);
}
return node;
}
public void delete(int k)
{
if (isEmpty())
System.out.println("Tree Empty");
else if (search(k) == false)
System.out.println("Sorry "+ k +" is not present");
else
{
root = delete(root, k);
Again, why is the delete function written like root=delete(.....
? Is it returning root =actual root element each time?
System.out.println(k+ " deleted from the tree");
}
}
private BSTNode delete(BSTNode root, int k)
{
BSTNode p, p2, n;
if (root.getData() == k)
{
BSTNode lt, rt;
lt = root.getLeft();
rt = root.getRight();
if (lt == null && rt == null)
return null;
else if (lt == null)
{
p = rt;
return p;
}
else if (rt == null)
{
p = lt;
return p;
}
else
{
//case when we delete node having both children.
p2 = rt;
p = rt;
//getting the min of the right child subtree in p variable .
while (p.getLeft() != null)
p = p.getLeft();
p.setLeft(lt);
Please explain what is happening here and why is p2 i.e rt being returned.
return p2;
}
}
if (k < root.getData())
{
n = delete(root.getLeft(), k);
root.setLeft(n);
}
else
{
n = delete(root.getRight(), k);
root.setRight(n);
}
return root;
}
public int countNodes()
{
return countNodes(root);
}