Remove all leaf nodes from the binary search tree

16 Mar, 2022
We have given a binary search tree and we want to delete the leaf nodes from the binary search tree. Examples:  
Input : 20 10 5 15 30 25 35
Output : Inorder before Deleting the leaf node
         5 10 15 20 25 30 35
         Inorder after Deleting the leaf node
         10 20 30

        This is the binary search tree where we
        want to delete the leaf node.
              20
           /     \
          10      30
         /  \    /  \
       5     15 25   35 

      After deleting the leaf node the binary 
      search tree looks like
              20
           /     \
          10      30
     
 
We traverse given Binary Search Tree in inorder way. During traversal, we check if current node is leaf, if yes, we delete it. Else we recur for left and right children. An important thing to remember is, we must assign new left and right children if there is any modification in roots of subtrees.  
C++
Java
Python3
C#
Javascript
// C++ program to delete leaf Node from// binary search tree.#include <bits/stdc++.h>using namespace std; struct Node {    int data;    struct Node* left;    struct Node* right;}; // Create a newNode in binary search tree.struct Node* newNode(int data){    struct Node* temp = new Node;    temp->data = data;    temp->left = temp->right = NULL;    return temp;} // Insert a Node in binary search tree.struct Node* insert(struct Node* root, int data){    if (root == NULL)        return newNode(data);    if (data < root->data)        root->left = insert(root->left, data);    else if (data > root->data)        root->right = insert(root->right, data);    return root;} // Function for inorder traversal in a BST.void inorder(struct Node* root){    if (root != NULL) {        inorder(root->left);        cout << root->data << " ";        inorder(root->right);    }} // Delete leaf nodes from binary search tree.struct Node* leafDelete(struct Node* root){    if (root == NULL)        return NULL;    if (root->left == NULL && root->right == NULL) {        free(root);        return NULL;    }     // Else recursively delete in left and right    // subtrees.    root->left = leafDelete(root->left);    root->right = leafDelete(root->right);     return root;} // Driver codeint main(){    struct Node* root = NULL;    root = insert(root, 20);    insert(root, 10);    insert(root, 5);    insert(root, 15);    insert(root, 30);    insert(root, 25);    insert(root, 35);    cout << "Inorder before Deleting the leaf Node." << endl;    inorder(root);    cout << endl;    leafDelete(root);    cout << "INorder after Deleting the leaf Node." << endl;    inorder(root);    return 0;}
// Java program to delete leaf Node from// binary search tree.class GfG {     static class Node {        int data;        Node left;        Node right;    }     // Create a newNode in binary search tree.    static Node newNode(int data)    {        Node temp = new Node();        temp.data = data;        temp.left = null;        temp.right = null;        return temp;    }     // Insert a Node in binary search tree.    static Node insert(Node root, int data)    {        if (root == null)            return newNode(data);        if (data < root.data)            root.left = insert(root.left, data);        else if (data > root.data)            root.right = insert(root.right, data);        return root;    }     // Function for inorder traversal in a BST.    static void inorder(Node root)    {        if (root != null) {            inorder(root.left);            System.out.print(root.data + " ");            inorder(root.right);        }    }     // Delete leaf nodes from binary search tree.    static Node leafDelete(Node root)    {        if (root == null) {            return null;        }        if (root.left == null && root.right == null) {            return null;        }         // Else recursively delete in left and right        // subtrees.        root.left = leafDelete(root.left);        root.right = leafDelete(root.right);         return root;    }     // Driver code    public static void main(String[] args)    {        Node root = null;        root = insert(root, 20);        insert(root, 10);        insert(root, 5);        insert(root, 15);        insert(root, 30);        insert(root, 25);        insert(root, 35);        System.out.println("Inorder before Deleting the leaf Node. ");        inorder(root);        System.out.println();        leafDelete(root);        System.out.println("INorder after Deleting the leaf Node. ");        inorder(root);    }}// This code is contributed by Prerna saini
# Python 3 program to delete leaf# Node from binary search tree. # Create a newNode in binary search tree.class newNode:     # Constructor to create a new node    def __init__(self, data):        self.data = data        self.left = None        self.right = None # Insert a Node in binary search tree.def insert(root, data):    if root == None:        return newNode(data)    if data < root.data:        root.left = insert(root.left, data)    else if data > root.data:        root.right = insert(root.right, data)    return root # Function for inorder traversal in a BST.def inorder(root):    if root != None:        inorder(root.left)        print(root.data, end = " ")        inorder(root.right) # Delete leaf nodes from binary search tree.def leafDelete(root):    if root == None:        return None    if root.left == None and root.right == None:        return None     # Else recursively delete in left    # and right subtrees.    root.left = leafDelete(root.left)    root.right = leafDelete(root.right)     return root # Driver codeif __name__ == '__main__':    root = None    root = insert(root, 20)    insert(root, 10)    insert(root, 5)    insert(root, 15)    insert(root, 30)    insert(root, 25)    insert(root, 35)    print("Inorder before Deleting the leaf Node.")    inorder(root)    leafDelete(root)    print()    print("INorder after Deleting the leaf Node.")    inorder(root)     # This code is contributed by PranchalK
// C# program to delete leaf Node from// binary search tree.using System; class GfG {     class Node {        public int data;        public Node left;        public Node right;    }     // Create a newNode in binary search tree.    static Node newNode(int data)    {        Node temp = new Node();        temp.data = data;        temp.left = null;        temp.right = null;        return temp;    }     // Insert a Node in binary search tree.    static Node insert(Node root, int data)    {        if (root == null)            return newNode(data);        if (data < root.data)            root.left = insert(root.left, data);        else if (data > root.data)            root.right = insert(root.right, data);        return root;    }     // Function for inorder traversal in a BST.    static void inorder(Node root)    {        if (root != null) {            inorder(root.left);            Console.Write(root.data + " ");            inorder(root.right);        }    }     // Delete leaf nodes from binary search tree.    static Node leafDelete(Node root)    {        if (root == null) {            return null;        }        if (root.left == null && root.right == null) {            return null;        }         // Else recursively delete in        // left and right subtrees.        root.left = leafDelete(root.left);        root.right = leafDelete(root.right);         return root;    }     // Driver code    public static void Main(String[] args)    {        Node root = null;        root = insert(root, 20);        insert(root, 10);        insert(root, 5);        insert(root, 15);        insert(root, 30);        insert(root, 25);        insert(root, 35);        Console.WriteLine("Inorder before Deleting"                          + "the leaf Node. ");        inorder(root);        Console.WriteLine();        leafDelete(root);        Console.WriteLine("INorder after Deleting"                          + "the leaf Node. ");        inorder(root);    }} // This code has been contributed// by PrinciRaj1992
<script> // JavaScript program to delete leaf Node from// binary search tree.class Node {    constructor() {        this.data = 0;        this.left = null;        this.right = null;    }}     // Create a newNode in binary search tree.    function newNode(data) {        var temp = new Node();        temp.data = data;        temp.left = null;        temp.right = null;        return temp;    }     // Insert a Node in binary search tree.    function insert(root , data) {        if (root == null)            return newNode(data);        if (data < root.data)            root.left = insert(root.left, data);        else if (data > root.data)            root.right = insert(root.right, data);        return root;    }     // Function for inorder traversal in a BST.    function inorder(root) {        if (root != null) {            inorder(root.left);            document.write(root.data + " ");            inorder(root.right);        }    }     // Delete leaf nodes from binary search tree.    function leafDelete(root) {        if (root == null) {            return null;        }        if (root.left == null && root.right == null) {            return null;        }         // Else recursively delete in left and right        // subtrees.        root.left = leafDelete(root.left);        root.right = leafDelete(root.right);         return root;    }     // Driver code             var root = null;        root = insert(root, 20);        insert(root, 10);        insert(root, 5);        insert(root, 15);        insert(root, 30);        insert(root, 25);        insert(root, 35);        document.write(        "Inorder before Deleting the leaf Node. <br/>"        );        inorder(root);        document.write("<br/>");        leafDelete(root);        document.write(        "INorder after Deleting the leaf Node. <br/>"        );        inorder(root); // This code is contributed by todaysgaurav </script>
Output:  
Inorder before Deleting the leaf node.
5 10 15 20 25 30 35
INorder after Deleting the leaf node.
10 20 30
Remove all leaf nodes from the binary search tree | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersRemove all leaf nodes from the binary search tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:42•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=1gW-fL6-vHE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk 
This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
 
prerna saini
PranchalKatiyar
princiraj1992
RajBhise
Ankur_Agarwal
gp6
todaysgaurav
simmytarika5
Binary Search Tree
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find postorder traversal of BST from preorder traversal
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Lowest Common Ancestor in a Binary Search Tree.
Optimal Binary Search Tree | DP-24
Merge Two Balanced Binary Search Trees
Convert a normal BST to Balanced BST
set vs unordered_set in C++ STL
Find the node with minimum value in a Binary Search Tree
Find k-th smallest element in BST (Order Statistics in BST)
Check if a given array can represent Preorder Traversal of Binary Search Tree