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:Â
Â
C++
// CPP implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Tree Nodeclass Node{public:Â Â Â Â int data;Â Â Â Â Node *left, *right;Â
    Node(int data) : data(data) {}};Â
// Method to perform inorder traversalvoid 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 treeint 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 nodevoid 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 nodevoid 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 Codeint 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
// Java Implementation of the approachpublic 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#
// C# implementation of the above approachusing 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 |
Javascript
<script>Â
// Javascript implementation of the above approachÂ
// Tree Nodeclass Node{Â Â Â Â constructor(data)Â Â Â Â {Â Â Â Â Â Â Â Â this.data = data;Â Â Â Â Â Â Â Â this.left = null;Â Â Â Â Â Â Â Â this.right = null;Â Â Â Â }}Â
// Method to perform inorder traversalfunction 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 treefunction 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 nodefunction 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 nodefunction 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 Codevar 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> |
Python3
#Python implementation for the above approachÂ
# Tree Nodeclass Node:    def __init__(self, data):        self.data = data        self.left = None        self.right = None#Method to perform inorder traversaldef 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 = Noneparent_of_last_node = None#Method to get the height of the treedef 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 nodedef 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 nodedef 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 |
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:Â
Â
C++
#include<bits/stdc++.h>using namespace std;Â
// C++ implementation of the approach// Tree Nodeclass Node {Â
   public:    int data;    Node *left, *right;Â
    Node(int data) : data(data) {}Â
} ;Â
// Function to perform the inorder traversal of the treevoid 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 treevoid 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 Codeint 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
// Java implementationimport 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
# Python program for the above approach# tree nodeclass Node:    def __init__(self, key):        self.data = key        self.left = None        self.right = NoneÂ
# function to perform the inorder traversal of the treedef 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 itselflastLevelLevelOrder = NoneparentOfLastNode = NoneÂ
# method to delete the last node# from the treedef 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#
// C# implementation of the approachusing 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
// JavaScript program for the above approach// Tree Nodeclass Node{Â Â Â Â constructor(data){Â Â Â Â Â Â Â Â this.data = data;Â Â Â Â Â Â Â Â this.left = null;Â Â Â Â Â Â Â Â this.right = null;Â Â Â Â }}Â
// Function to perform the inorder traversal of the treefunction 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 treefunction 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 codelet 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) |
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 .
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Find More here on that Topic: geeksforgeeks.org/delete-the-last-leaf-node-in-a-binary-tree/ […]
… [Trackback]
[…] Find More here to that Topic: geeksforgeeks.org/delete-the-last-leaf-node-in-a-binary-tree/ […]