Delete the last leaf node in a Binary Tree

Given a Binary Tree, the task is to find and DELETE the last leaf node.

The leaf node is a node with no children. The last leaf node would be the node that is traversed last in sequence during Level Order Traversal. The problem statement is to identify this last visited node and delete this particular node.

Examples:



 
Input: 
Given Tree is: 
          6
       /     \
      5       4
    /   \       \
   1     2       5 

Level Order Traversal is: 6 5 4 1 2 5
Output: 
After deleting the last node (5),
the tree would look like as follows. 

          6
       /     \
      5       4
    /   \  
   1     2 
Level Order Traversal is: 6 5 4 1 2

Input: 
Given tree is: 
           1
        /     \
      3        10
    /   \     /   \
   2     15   4     5                        
        /                    
       1    
Level Order Traversal is: 1 3 10 2 15 4 5 1
Output: 
After deleting the last node (1),
the tree would look like as follows.

           1
        /     \
      3        10
    /   \     /   \
   2     15   4     5                        

Level Order Traversal is: 1 3 10 2 15 4 5

This problem is slightly different from Delete leaf node with value as X wherein we are right away given the value of last leaf node (X) to be deleted, based on which we perform checks and mark the parent node as null to delete it.

This approach would identify the last present leaf node on last level of the tree and would delete it.

Approach 1: Traversing last level nodes and keeping track of Parent and traversed node.

This approach would traverse each node until we reach the last level of the given binary tree. While traversing, we keep track of the last traversed node and its Parent.

Once done with traversal, Check if the parent has Right Child, if yes, set it to NULL. If no, set the left pointer to NULL

Below is the implementation of the approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Implementation of the approach
public class DeleteLastNode {
  
    // Tree Node
    static class Node {
  
        Node left, right;
        int data;
  
        Node(int data)
        {
            this.data = data;
        }
    }
  
    // Method to perform inorder traversal
    public void inorder(Node root)
    {
        if (root == null)
            return;
  
        inorder(root.left);
        System.out.print(root.data + " ");
        inorder(root.right);
    }
  
    // To keep track of last processed
    // nodes parent and node itself.
    public static Node lastNode;
    public static Node parentOfLastNode;
  
    // Method to get the height of the tree
    public int height(Node root)
    {
  
        if (root == null)
            return 0;
  
        int lheight = height(root.left) + 1;
        int rheight = height(root.right) + 1;
  
        return Math.max(lheight, rheight);
    }
  
    // Method to delete last leaf node
    public void deleteLastNode(Node root)
    {
  
        int levelOfLastNode = height(root);
  
        // Get all nodes at last level
        getLastNodeAndItsParent(root,
                                levelOfLastNode,
                                null);
  
        if (lastNode != null
            && parentOfLastNode != null) {
  
            if (parentOfLastNode.right != null)
                parentOfLastNode.right = null;
            else
                parentOfLastNode.left = null;
        }
        else
            System.out.println("Empty Tree");
    }
  
    // Method to keep track of parents
    // of every node
    public void getLastNodeAndItsParent(Node root,
                                        int level,
                                        Node parent)
    {
  
        if (root == null)
            return;
  
        // The last processed node in
        // Level Order Traversal has to
        // be the node to be deleted.
        // This will store the last
        // processed node and its parent.
        if (level == 1) {
            lastNode = root;
            parentOfLastNode = parent;
        }
        getLastNodeAndItsParent(root.left,
                                level - 1,
                                root);
        getLastNodeAndItsParent(root.right,
                                level - 1,
                                root);
    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        Node root = new Node(6);
        root.left = new Node(5);
        root.right = new Node(4);
        root.left.left = new Node(1);
        root.left.right = new Node(2);
        root.right.right = new Node(5);
  
        DeleteLastNode deleteLastNode = new DeleteLastNode();
  
        System.out.println("Inorder traversal "
                           + "before deletion "
                           + "of last node : ");
  
        deleteLastNode.inorder(root);
  
        deleteLastNode.deleteLastNode(root);
  
        System.out.println("\nInorder traversal "
                           + "after deletion of "
                           + "last node : ");
        deleteLastNode.inorder(root);
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the above approach
using System;
      
class GFG
{
  
    // Tree Node
    public class Node
    {
        public Node left, right;
        public int data;
  
        public Node(int data)
        {
            this.data = data;
        }
    }
  
    // Method to perform inorder traversal
    public void inorder(Node root)
    {
        if (root == null)
            return;
  
        inorder(root.left);
        Console.Write(root.data + " ");
        inorder(root.right);
    }
  
    // To keep track of last processed
    // nodes parent and node itself.
    public static Node lastNode;
    public static Node parentOfLastNode;
  
    // Method to get the height of the tree
    public int height(Node root)
    {
        if (root == null)
            return 0;
  
        int lheight = height(root.left) + 1;
        int rheight = height(root.right) + 1;
  
        return Math.Max(lheight, rheight);
    }
  
    // Method to delete last leaf node
    public void deleteLastNode(Node root)
    {
        int levelOfLastNode = height(root);
  
        // Get all nodes at last level
        getLastNodeAndItsParent(root,
                                levelOfLastNode,
                                null);
  
        if (lastNode != null && 
            parentOfLastNode != null)
        {
            if (parentOfLastNode.right != null)
                parentOfLastNode.right = null;
            else
                parentOfLastNode.left = null;
        }
        else
            Console.WriteLine("Empty Tree");
    }
  
    // Method to keep track of parents
    // of every node
    public void getLastNodeAndItsParent(Node root,
                                        int level,
                                        Node parent)
    {
        if (root == null)
            return;
  
        // The last processed node in
        // Level Order Traversal has to
        // be the node to be deleted.
        // This will store the last
        // processed node and its parent.
        if (level == 1)
        {
            lastNode = root;
            parentOfLastNode = parent;
        }
        getLastNodeAndItsParent(root.left,
                                level - 1,
                                root);
        getLastNodeAndItsParent(root.right,
                                level - 1,
                                root);
    }
  
    // Driver Code
    public static void Main(String[] args)
    {
        Node root = new Node(6);
        root.left = new Node(5);
        root.right = new Node(4);
        root.left.left = new Node(1);
        root.left.right = new Node(2);
        root.right.right = new Node(5);
  
        GFG deleteLastNode = new GFG();
  
        Console.WriteLine("Inorder traversal "
                            "before deletion "
                             "of last node : ");
  
        deleteLastNode.inorder(root);
  
        deleteLastNode.deleteLastNode(root);
  
        Console.WriteLine("\nInorder traversal "
                            "after deletion of "
                                  "last node : ");
        deleteLastNode.inorder(root);
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

Inorder traversal before deletion of last node : 
1 5 2 6 4 5 
Inorder traversal after deletion of last node : 
1 5 2 6 4

Time Complexity: O(N)
Since each node would be traversed once, the time taken would be linear to the number of nodes in a given tree.

Approach 2: Performing Level Order Traversal on given Binary Tree using Queue and tracking Parent and last traversed node.

This is a Non-Recursive way of achieving above Approach 1. We perform the Level Order Traversal using Queue and keeping track of every visited node and its parent. The last visited node would be the last node that is to be deleted.

Below is the implementation of the approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation
import java.util.LinkedList;
import java.util.Queue;
  
  
public class DeleteLastNode {
      
    // Tree Node
    static class Node {
  
        Node left, right;
        int data;
  
        Node(int data)
        {
            this.data = data;
        }
    
  
    // Function to perform the inorder traversal of the tree
    public void inorder(Node root)
    {
        if (root == null)
            return;
  
        inorder(root.left);
        System.out.print(root.data + " ");
        inorder(root.right);
    }
  
    // To keep track of last
    // processed nodes parent
    // and node itself.
    public static Node lastLevelLevelOrder;
    public static Node parentOfLastNode;
  
    // Method to delete the last node
    // from the tree
    public void deleteLastNode(Node root)
    {
  
        // If tree is empty, it
        // would return without
        // any deletion
        if (root == null)
            return;
  
        // The queue would be needed
        // to maintain the level order
        // traversal of nodes
        Queue<Node> queue = new LinkedList<>();
  
        queue.offer(root);
  
        // The traversing would
        // continue untill all
        // nodes are traversed once
        while (!queue.isEmpty()) {
  
            Node temp = queue.poll();
  
            // If there is left child
            if (temp.left != null) {
                queue.offer(temp.left);
  
                // For every traverssed node,
                // we would check if it is a
                // leaf node by checking if
                // current node has children to it
                if (temp.left.left == null
                    && temp.left.right == null) {
  
                    // For every leaf node
                    // encountered, we would
                    // keep not of it as
                    // "Previously Visided Leaf node.
                    lastLevelLevelOrder = temp.left;
                    parentOfLastNode = temp;
                }
            }
  
            if (temp.right != null) {
                queue.offer(temp.right);
  
                if (temp.right.left == null
                    && temp.right.right == null) {
  
                    // For every leaf node
                    // encountered, we would
                    // keep not of it as
                    // "Previously Visided Leaf node.
                    lastLevelLevelOrder = temp.right;
                    parentOfLastNode = temp;
                }
            }
        }
  
        // Once out of above loop.
        // we would certainly have
        // last visited node, which
        // is to be deleted and its
        // parent node.
  
        if (lastLevelLevelOrder != null
            && parentOfLastNode != null) {
  
            // If last node is right child
            // of parent, make right node
            // of its parent as NULL or
            // make left node as NULL
            if (parentOfLastNode.right != null)
                parentOfLastNode.right = null;
            else
                parentOfLastNode.left = null;
        }
        else
            System.out.println("Empty Tree");
    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        Node root = new Node(6);
        root.left = new Node(5);
        root.right = new Node(4);
        root.left.left = new Node(1);
        root.left.right = new Node(2);
        root.right.right = new Node(5);
  
        DeleteLastNode deleteLastNode
            = new DeleteLastNode();
  
        System.out.println("Inorder traversal "
                           + "before deletion of "
                           + "last node : ");
        deleteLastNode.inorder(root);
  
        deleteLastNode.deleteLastNode(root);
  
        System.out.println("\nInorder traversal "
                           + "after deletion "
                           + "of last node : ");
  
        deleteLastNode.inorder(root);
    }
}

chevron_right


filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
using System.Collections.Generic;
public class DeleteLastNode {
       
    // Tree Node
    public class Node {
   
        public Node left, right;
        public int data;
   
        public Node(int data)
        {
            this.data = data;
        }
    
   
    // Function to perform the inorder traversal of the tree
    public void inorder(Node root)
    {
        if (root == null)
            return;
   
        inorder(root.left);
        Console.Write(root.data + " ");
        inorder(root.right);
    }
   
    // To keep track of last
    // processed nodes parent
    // and node itself.
    public static Node lastLevelLevelOrder;
    public static Node parentOfLastNode;
   
    // Method to delete the last node
    // from the tree
    public void deleteLastNode(Node root)
    {
   
        // If tree is empty, it
        // would return without
        // any deletion
        if (root == null)
            return;
   
        // The queue would be needed
        // to maintain the level order
        // traversal of nodes
        Queue<Node> queue = new Queue<Node>();
   
        queue.Enqueue(root);
   
        // The traversing would
        // continue untill all
        // nodes are traversed once
        while (queue.Count!=0) {
   
            Node temp = queue.Dequeue();
   
            // If there is left child
            if (temp.left != null) {
                queue.Enqueue(temp.left);
   
                // For every traverssed node,
                // we would check if it is a
                // leaf node by checking if
                // current node has children to it
                if (temp.left.left == null
                    && temp.left.right == null) {
   
                    // For every leaf node
                    // encountered, we would
                    // keep not of it as
                    // "Previously Visided Leaf node.
                    lastLevelLevelOrder = temp.left;
                    parentOfLastNode = temp;
                }
            }
   
            if (temp.right != null) {
                queue.Enqueue(temp.right);
   
                if (temp.right.left == null
                    && temp.right.right == null) {
   
                    // For every leaf node
                    // encountered, we would
                    // keep not of it as
                    // "Previously Visided Leaf node.
                    lastLevelLevelOrder = temp.right;
                    parentOfLastNode = temp;
                }
            }
        }
   
        // Once out of above loop.
        // we would certainly have
        // last visited node, which
        // is to be deleted and its
        // parent node.
   
        if (lastLevelLevelOrder != null
            && parentOfLastNode != null) {
   
            // If last node is right child
            // of parent, make right node
            // of its parent as NULL or
            // make left node as NULL
            if (parentOfLastNode.right != null)
                parentOfLastNode.right = null;
            else
                parentOfLastNode.left = null;
        }
        else
            Console.WriteLine("Empty Tree");
    }
   
    // Driver Code
    public static void Main(String[] args)
    {
   
        Node root = new Node(6);
        root.left = new Node(5);
        root.right = new Node(4);
        root.left.left = new Node(1);
        root.left.right = new Node(2);
        root.right.right = new Node(5);
   
        DeleteLastNode deleteLastNode
            = new DeleteLastNode();
   
        Console.WriteLine("Inorder traversal "
                           + "before deletion of "
                           + "last node : ");
        deleteLastNode.inorder(root);
   
        deleteLastNode.deleteLastNode(root);
   
        Console.WriteLine("\nInorder traversal "
                           + "after deletion "
                           + "of last node : ");
   
        deleteLastNode.inorder(root);
    }
}
  
// This code contributed by Rajput-Ji

chevron_right


Output:

Inorder traversal before deletion of last node : 
1 5 2 6 4 5 
Inorder traversal after deletion of last node : 
1 5 2 6 4

Time Complexity: O(N)

Since every node would be visited once, the time taken would be linear to the number of nodes present in the tree.
Auxilary Space: O(N)
Since we would be maintaining a queue to do the level order traversal, the space consumed would be O(N).



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : 29AjayKumar, Rajput-Ji



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.