Here is the code for a BST ,traversing in bottom-up manner and trying to delete the leaf nodes if its value is equal to "k", so if the leaves are deleted and the new leaf formed has the value "k", i am also deleting them.
So this is the reasonI i am traversing in bottom-up fashion. To delete the leaf I am just assigning the Node reference to null but which actually does not delete it because java is pass by value, is there anyway that i can make changes to the original tree in the following part of the code:
if(l==null&&r==null&&n.k==k){
n=null;
return n;
}
but after printing the tree values its showing up the same tree as before, but when I change the node value n.k=0
the values are changing, but its not taking the null reference.
Why is null not assigned to the nodes?
below is the code, running this code prints the same tree again after the **************************
:
class Node{
Node(int k){
this.k = k;
}
int k;
Node right;
Node left;
}
public class Testing {
static void preOrder(Node n){
if(n==null);
else{
preOrder(n.left);
preOrder(n.right);
System.out.println(n.k);
}
}
static Node del_leaves(Node n,int k){
if(n==null)
return null;
else{
Node l=null,r=null;
if(n.left!=null)
l = del_leaves(n.left,k);
if(n.right!=null)
r = del_leaves(n.right,k);
if(l==null&&r==null&&n.k==k){
n=null;
return n;
}
else
return n;
}
}
public static void main(String args[]){
Node root = new Node(10);
Node a = new Node(5);
Node b = new Node(5);
Node c = new Node(5);
Node d = new Node(5);
Node e = new Node(5);
root.left=a;
root.right=b;
a.left=c;
a.right=d;
b.left=e;
preOrder(root);
Node ret_root = del_leaves(root,5);
System.out.println("*****************************");
preOrder(ret_root);
}
}