Open In App

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: 
 

// CPP implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Tree Node
class Node
{
public:
    int data;
    Node *left, *right;
 
    Node(int data) : data(data) {}
};
 
// Method to perform inorder traversal
void inorder(Node *root)
{
    if (root == NULL)
        return;
 
    inorder(root->left);
    cout << root->data << " ";
    inorder(root->right);
}
 
// To keep track of last processed
// nodes parent and node itself.
Node *lastNode, *parentOfLastNode;
 
// Method to get the height of the tree
int height(Node *root)
{
    if (root == NULL)
        return 0;
 
    int lheight = height(root->left) + 1;
    int rheight = height(root->right) + 1;
 
    return max(lheight, rheight);
}
 
// Method to keep track of parents
// of every node
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);
}
 
// Method to delete last leaf node
void deleteLastNode(Node *root)
{
    int levelOfLastNode = height(root);
    getLastNodeAndItsParent(root, levelOfLastNode, NULL);
 
    if (lastNode and parentOfLastNode)
    {
        if (parentOfLastNode->right)
            parentOfLastNode->right = NULL;
        else
            parentOfLastNode->left = NULL;
    }
    else
        cout << "Empty Tree\n";
}
 
// Driver Code
int main()
{
    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);
 
    cout << "Inorder traversal before deletion of last node :\n";
    inorder(root);
 
    deleteLastNode(root);
 
    cout << "\nInorder traversal after deletion of last node :\n";
    inorder(root);
 
    return 0;
}
 
// This code is contributed by
// sanjeev2552

                    
// 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);
    }
}

                    
// 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

                    
<script>
 
// Javascript implementation of the above approach
 
// Tree Node
class Node
{
    constructor(data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
// Method to perform inorder traversal
function inorder(root)
{
    if (root == null)
        return;
    inorder(root.left);
    document.write(root.data + " ");
    inorder(root.right);
}
// To keep track of last processed
// nodes parent and node itself.
var lastNode = null;
var parentOfLastNode = null;
// Method to get the height of the tree
function height(root)
{
    if (root == null)
        return 0;
    var lheight = height(root.left) + 1;
    var rheight = height(root.right) + 1;
    return Math.max(lheight, rheight);
}
 
// Method to delete last leaf node
function deleteLastNode(root)
{
    var 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
function getLastNodeAndItsParent(root, level, 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
var 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);
document.write("Inorder traversal " +
                    "before deletion " +
                     "of last node :<br>");
inorder(root);
deleteLastNode(root);
document.write("<br>Inorder traversal " +
                    "after deletion of " +
                          "last node :<br>");
inorder(root);
 
// This code is contributed by rrrtnx.
</script>

                    
#Python implementation for the above approach
 
# Tree Node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
#Method to perform inorder traversal
def inorder(root):
    if root is None:
        return
    inorder(root.left)
    print(root.data, end=" ")
    inorder(root.right)
# To keep track of last processed
# nodes parent and node itself.
last_node = None
parent_of_last_node = None
#Method to get the height of the tree
def height(root):
    if root is None:
        return 0
    lheight = height(root.left) + 1
    rheight = height(root.right) + 1
    return max(lheight, rheight)
#Method to delete last leaf node
def get_last_node_and_its_parent(root, level, parent):
    global last_node, parent_of_last_node
    if root is None:
        return
    if level == 1:
        last_node = root
        parent_of_last_node = parent
    get_last_node_and_its_parent(root.left, level - 1, root)
    get_last_node_and_its_parent(root.right, level - 1, root)
#Method to keep track of parents
#of every node
def delete_last_node(root):
    global last_node, parent_of_last_node
    level_of_last_node = height(root)
    get_last_node_and_its_parent(root, level_of_last_node, None)
    if last_node and parent_of_last_node:
        if parent_of_last_node.right:
            parent_of_last_node.right = None
        else:
            parent_of_last_node.left = None
    else:
        print("Empty Tree")
 
#Driver code      
root = Node(6)
root.left = Node(5)
root.right = Node(4)
root.left.left = Node(1)
root.left.right = Node(2)
root.right.right = Node(5)
 
print("Inorder traversal before deletion of last node:")
inorder(root)
 
delete_last_node(root)
 
print("\nInorder traversal after deletion of last node:")
inorder(root)
#This code is contributed by Potta Lokesh

                    

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: 

Space complexity :- O(H)
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: 
 

#include<bits/stdc++.h>
using namespace std;
 
// C++ implementation of the approach
// Tree Node
class Node {
 
   public:
    int data;
    Node *left, *right;
 
    Node(int data) : data(data) {}
 
} ;
 
// Function to perform the inorder traversal of the tree
void inorder(Node* root)
{
    if (root == NULL)
        return;
 
    inorder(root->left);
    cout<<root->data << " ";
    inorder(root->right);
}
 
// To keep track of last
// processed nodes parent
// and node itself->
Node* lastLevelLevelOrder;
Node* parentOfLastNode;
 
// Method to delete the last node
// from the tree
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;   
    queue.push(root);
 
    // The traversing would
    // continue until all
    // nodes are traversed once
    while (!queue.empty()) {
 
        Node* temp = queue.front();
        queue.pop();
 
        // If there is left child
        if (temp->left != NULL) {
            queue.push(temp->left);
 
            // For every traversed 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 Visited Leaf node->
                lastLevelLevelOrder = temp->left;
                parentOfLastNode = temp;
            }
        }
 
        if (temp->right != NULL) {
            queue.push(temp->right);
 
            if (temp->right->left == NULL
                && temp->right->right == NULL) {
 
                // For every leaf node
                // encountered, we would
                // keep not of it as
                // "Previously Visited 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
        cout<<"Empty Tree";
}
 
// Driver Code
int main()
{
    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();
     
    cout<<"Inorder traversal "
                       << "before deletion of "
                       << "last node : "<<endl;
    inorder(root);
     
    deleteLastNode(root);
     
    cout<<"\nInorder traversal "
                       << "after deletion "
                       << "of last node : "<<endl;
     
    inorder(root);
}

                    
// 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 until 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 traversed 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 Visited 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 Visited 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);
    }
}

                    
# Python program for the above approach
# tree node
class Node:
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
# function to perform the inorder traversal of the tree
def inorder(root):
    if(root is not None):
        inorder(root.left)
        print(root.data)
        inorder(root.right)
 
# to keep track of last processed nodes parent
# and node itself
lastLevelLevelOrder = None
parentOfLastNode = None
 
# method to delete the last node
# from the tree
def deleteLastNode(root):
    # if tree is empty, it would return without
    # any deletion
    if(root is None):
        return
     
    # The queue would be needed to maintain the
    # level order traversal of nodes
    queue = []
    queue.append(root)
     
    # the traversing woule continue until all nodes
    # are traversed once
    while(len(queue) > 0):
        temp = queue.pop(0)
        # if there is left child
        if(temp.left is not None):
            queue.append(temp.left)
             
            # for every traversed node, we would check if it is a
            # leaf node by checking if current node has children to it
            if(temp.left.left is None and temp.left.right is None):
                # for every leaf node encountered, we would
                # keep not of it as "Previously Visited Leaf node"
                lastLevelLevelOrder = temp.left
                parentOfLastNode = temp
         
        if(temp.right is not None):
            queue.append(temp.right)
             
            if(temp.right.left is None and temp.right.right is None):
                # for every leaf node encountered, we would
                # keep not of it as "Previously Visited 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 is not None and parentOfLastNode is not None):
        # 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 is not None):
            parentOfLastNode.right = None
        else:
            parentOfLastNode.left = None
    else:
        print("Empty Tree")
 
root = Node(6)
root.left = Node(5)
root.right = Node(4)
root.left.left = Node(1)
root.left.right = Node(2)
root.right.right = Node(5)
 
print("Inorder traversal before deletion of last node : ")
inorder(root)
 
deleteLastNode(root)
 
print("Inorder traversal after deletion of last node : ")
inorder(root)
 
# This code is contributed by Kirti Agarwal

                    
// 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 until 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 traversed 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 Visited 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 Visited 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

                    
// JavaScript program for the above approach
// Tree Node
class Node{
    constructor(data){
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
// Function to perform the inorder traversal of the tree
function inorder(root){
    if(root != null){
        inorder(root.left);
        console.log(root.data + " ");
        inorder(root.right);
    }
}
 
// To keep track of last
// processed nodes parent
// and node itself->
let lastLevelLevelOrder;
let parentOfLastNode;
 
// Method to delete the last node
// from the tree
function deleteLastNode(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
    let queue = []
    queue.push(root);
     
    // The traversing would
    // continue until all
    // nodes are traversed once
    while(queue.length > 0){
        let temp = queue.shift();
         
        // If there is left child
        if(temp.left != null){
            queue.push(temp.left);
             
            // For every traversed 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 Visited Leaf node->
                lastLevelLevelOrder = temp.left;
                parentOfLastNode = temp;
            }
        }
         
        if(temp.right != null){
            queue.push(temp.right);
             
            if(temp.right.left == null && temp.right.right == null){
                // For every leaf node
                // encountered, we would
                // keep not of it as
                // "Previously Visited 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.log("Empty Tree");
    }
}
 
// Driver code
let 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);
 
console.log("Inorder Traversal before deletion of last node : ");
inorder(root);
 
deleteLastNode(root);
 
console.log("Inorder Traversal after deletion of last node : ");
inorder(root);
 
// This code is contributed by Yash Agarwal(yashagarwal2852002)

                    

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: 
Since every node would be visited once, the time taken would be linear to the number of nodes present in the tree. 
Auxiliary Space: 
Since we would be maintaining a queue to do the level order traversal, the space consumed would be .
 


Article Tags :