Remove leaves from a binary tree using recursion - java

I tried to do this using this logic but I am getting error
public static void removeLeaves(BinaryTreeNode<Integer> root) {
BinaryTreeNode<Integer> temp = root;
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
root = null;
}
removeLeaves(temp.left);
removeLeaves(temp.right);
}
Whole tree is getting printed as it is. Please help me out without changing my logic.

In your if statement
if(root.left==null && root.right==null)
{
BinaryTreeNode<Integer> temp = null;
root = temp;
}
You are declaring root as temp, which is null, then pass that temp into the removeLeaves function. So you are passing null into that function when the if statement is true.

BinaryTreeNode<Integer> temp = null;
root = temp;
basically sets root to null and then you call root.left => NPE
You might want to add the necessarily null checks, and probably rethink your function as a whole.

You need to check each root individually for null. Your if statement
if(root.left==null && root.right==null)
{
BinaryTreeNode<Integer> temp = null;
root = temp;
}
only checks if both roots are null. But say there is no left leaf (root.left is null) and there is only a right leaf, you still execute on the left side
removeLeaves(root.left);
However, we already know that root.left is null. I suggest adding individual checks before each call to removeLeaves() or modifying your existing if statement.

I'm not convinced this isn't a homework assignment, but here goes.
The null exception is because you are still calling removeLeaves() even when both the left and right sides are null. Have you tried putting an else after your main IF()?
public static void removeLeaves(BinaryTreeNode<Integer> root)
{
if(root == null)
{
return; // enclosing conditionals in braces is better form, saves lots of headaches later
}
if(root.left==null && root.right==null)
{
BinaryTreeNode<Integer> temp = null;
root = temp;
}
else //at least one is not null
{
removeLeaves(root.left);
removeLeaves(root.right);
}
}

Related

Infinite recursion in Java with splay trees

I am trying to write a "contains" method for a splay tree to figure out if a node is already in the tree. I give this method a node to start searching and a string key to use find the corresponding node. I think I have a pretty good handle on recursion, but I am stumped by this. I've bolded the two lines that are causing the infinite recursion, but I'm stuck because, unless you somehow have a tree with an infinite number of elements, wouldn't the left and/or right elements have to be null at some point? They cannot be != to null forever! I might be losing my mind but I would very much appreciate any clarification on how to create a stronger base case.
tldr: how is it possible for this function to recurse infinitely when we have to run into null at some point?!
public BST_Node containsNode(BST_Node node, String s) {
BST_Node result = null;
if (node == null) {
return null;
}
if (node.data.compareTo(s) == 0) {
splay(node);
return node;
}
if (node.left != null) {
result = containsNode(node.left, s); //recursion here
}
if (result == null && node.right != null) {
result = right.containsNode(node.right, s); //recursion here
}
return result;
}
}

Increase each node's value in a binary tree by 1

So the exercise I am trying to do is:
Write a recursive function to increment by one the value for every node in the binary tree pointed at by "root" then return the modified tree. Assume that nodes store integer values. (-1 means a NULL pointer)
The code I have so far is:
public BinNode BTinc(BinNode root)
{
if (root.right == null && root.left == null){
root.setValue(root.value() + 1);
return root;
}
if (root.left != null) {
root.left.setValue(root.left.value() + 1);
return BTinc(root.left);
}
if (root.right != null) {
root.right.setValue(root.right.value() + 1);
return BTinc(root.right);
}
return root;
}
The problem I am having so far occurs when the root being passed in is -1, in which I get a null pointer exception. I am a bit confused on how this is happening. Is it because I am trying to access the right and left pointers of the null pointer?
in which I get a null pointer exception. I am a bit confused on how
this is happening
you cannot just perform root.setValue(root.value() + 1); because what if the root is null?
you'll need to check if root is not equal to null prior to performing root.setValue.
if (root != null && root.right == null && root.left == null){ // if both left and right nodes are null then simply return root
root.setValue(root.value() + 1);
return root;
}
it's then up to you to set the appropriate value for the root.
Actually, you don't need to check if the left or right node is null or not, it's inefficient. "You do not look at the children to decide whether to make a recursive call." Just access the root and add value and leave the recursive call to do the rest.
public BinNode BTinc(BinNode root){
if (root != null) {
root.setValue(root.value() + 1);
BTinc (root.left());
BTinc (root.right());
}
return root;
}

How can i find the parent of the cursor in a binary tree without using a parent reference node

I am trying move cursor to it's parent node in a binary tree. I want to do it recursively without using a keeping a node to keep track of the parent. I think my base/stoping case is correct but I believe the last two if statement is wrong. Im not sure on how to go about it. Any advice will be helpful. Thank you.
public void cursorToParent()
{
TreeNode parent = root;
if(cursor == root )
return;
if(parent.getLeft().equals(cursor) || parent.getRight().equals(cursor) )
cursor = parent;
else
if(parent.getLeft()!=null)
{
parent = parent.getLeft();
cursorToParent();
}
if(parent.getLeft()!=null)
{
parent = parent.getLeft();
cursorToParent();
}
}
It's needed to pass the current processing node to the method. So there has to be method cursorToParentImpl() which will be called with root from the former method:
public boolean cursorToParentImpl(TreeNode current)
{
if(cursor == current )
return false;
if(current.getLeft () == cursor || current.getRight() == cursor) {
cursor = current;
return true;
}
else { // note the missing parenthesis too
if(current.getLeft()!=null) {
if (cursorToParentImpl(current.getLeft()))
return true;
}
if(current.getRight()!=null) {
if (cursorToParentImpl(current.getRight()))
return true;
}
}
return false;
}
And call it:
public void cursorToParent()
{
if (cursor == root)
return;
cursorToParentImpl(root);
}
Also you may avoid calling equals() and just use == operator as here it should rather compare the reference to the nodes.

NullPointerException in a while loop using a Binary Tree node

I am using a binary tree structure here. I am getting a "NullPointerException" from the line containing the while statement. I am completely confused about why that would be.
BinaryTreeNode<CharData> currNode = theTree.findValue(data);
// Move up the Binary Tree to create code.
while(currNode.getParent() != null) {
// The loop does some stuff that doesn't
// affect what is assigned to currNode.
// Move to the parent node for the next iteration.
currNode = currNode.getParent();
} // End the while loop.
return code; // Return the string of binary code.
Find value is a method from my BinaryTree class that searches for and finds the node containing specific data. I know this works from testing it separately outside of this implementation.
The only reason why the while-loop statement can throw a NPE is, when currNode is null. I suspect findValue() returned null.
I guess one fix (when you care about the topmost node) would be:
while(currentNode != null) {
rootNode = currentNode;
currentNode = currentNode.getParent();
}
Or the typical pattern which relies on boolean shortcut evaluation:
while(curentNode != null && currentNode.getParent() != null)
Or my prefered solution using guards:
if (currentNode == null)
throw NotFound(); // or return something
while(curentNode.getParent() != null) {
If you see the code:
BinaryTreeNode<CharData> currNode = theTree.findValue(data);
I guess, currNode is getting some value if findValue() able to search data else it is returning NULL values.
When it returns a NULL value it will throw NPE.
To avoid it, you can modify your code a little bit.
while(currNode != null && currNode.getParent != null) {
// your code here
}

Trying to create a removeLastElement using recursion

I need to make a method that removes the last element of a LinkedList using recursion.
This is what I have so far but it doesn't seem to be removing the node...when i call list.size() it is still the same size with the same values. What am I doing wrong here?
This is for Java by the way
public void removeLastElement(Node curr){
if (curr == null)
return;
else{
if(curr.next == null)
curr = null;
else
removeLastElement(curr.next);
}
}
In a LinkedList to remove the last element you have to get the penultimate element and set
curr.next = null
You're in the right way to get the recurrent function to remove the last node. The problem is you're identifying the penultimate node with curr.next == null, if you got it, you nullify it, but that's your actual input! So, you must check if the actual node is the antepenultimate node on the list:
if (curr.next.next == null) {
curr.next = null; //Now you're modifying the data in your input.
}
With this change, there are more basic cases to check, but that's up to you, my friend.
Boolean deleteLast(Node n)
{
if(n.next == null)
return true;
if(deleteLast(n.next))
{
n.next = null;
return false;
}
return false;
}
Node deleteLast(Node n) {
if (n.next == null)
return null;
n.next = deleteLast(n.next);
return this;
}
The general idea is you ask the next node "hey, can you tell me where you are, and delete your last node?" The last node can then just say "I'm nowhere" and it'll all fall into place.
This is very similar to Aadi's answer, just using Nodes instead of booleans.

Categories