Delete leaf nodes with value as x

30 Jun, 2021
Given a binary tree and a target integer x, delete all the leaf nodes having value as x. Also, delete the newly formed leaves with the target value as x.Example:  
Input : x = 5  
            6
         /     \
        5       4
      /   \       \
     1     2       5 
Output : 
            6
         /     \
        5       4
      /   \  
     1     2 
Inorder Traversal is 1 5 2 6 4
Source: Microsoft InterviewWe traverse the tree in postorder fashion and recursively delete the nodes. The approach is very similar to this and this problem.  
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.
C++
Java
Python3
C#
Javascript
// CPP code to delete all leaves with given// value.#include <bits/stdc++.h>using namespace std; // A binary tree nodestruct Node {    int data;    struct Node *left, *right;}; // A utility function to allocate a new nodestruct Node* newNode(int data){    struct Node* newNode = new Node;    newNode->data = data;    newNode->left = newNode->right = NULL;    return (newNode);} Node* deleteLeaves(Node* root, int x){    if (root == NULL)        return nullptr;    root->left = deleteLeaves(root->left, x);    root->right = deleteLeaves(root->right, x);     if (root->data == x && root->left == NULL &&                          root->right == NULL) {                return nullptr;    }    return root;} void inorder(Node* root){    if (root == NULL)        return;    inorder(root->left);    cout << root->data << " ";    inorder(root->right);} // Driver programint main(void){    struct Node* root = newNode(10);    root->left = newNode(3);    root->right = newNode(10);    root->left->left = newNode(3);    root->left->right = newNode(1);    root->right->right = newNode(3);    root->right->right->left = newNode(3);    root->right->right->right = newNode(3);    deleteLeaves(root, 3);    cout << "Inorder traversal after deletion : ";    inorder(root);    return 0;}
// Java code to delete all leaves with given// value.class GfG { // A binary tree nodestatic class Node {    int data;    Node left, right;} // A utility function to allocate a new nodestatic Node newNode(int data){    Node newNode = new Node();    newNode.data = data;    newNode.left = null;    newNode.right = null;    return (newNode);} static Node deleteLeaves(Node root, int x){    if (root == null)        return null;    root.left = deleteLeaves(root.left, x);    root.right = deleteLeaves(root.right, x);     if (root.data == x && root.left == null && root.right == null) {         return null;    }    return root;} static void inorder(Node root){    if (root == null)        return;    inorder(root.left);    System.out.print(root.data + " ");    inorder(root.right);} // Driver programpublic static void main(String[] args){    Node root = newNode(10);    root.left = newNode(3);    root.right = newNode(10);    root.left.left = newNode(3);    root.left.right = newNode(1);    root.right.right = newNode(3);    root.right.right.left = newNode(3);    root.right.right.right = newNode(3);    deleteLeaves(root, 3);    System.out.print("Inorder traversal after deletion : ");    inorder(root);}}
# Python3 code to delete all leaves# with given value. # A utility class to allocate a new nodeclass newNode:    def __init__(self, data):        self.data = data        self.left = self.right = None def deleteLeaves(root, x):    if (root == None):        return None    root.left = deleteLeaves(root.left, x)    root.right = deleteLeaves(root.right, x)     if (root.data == x and        root.left == None and        root.right == None):        return None    return root def inorder(root):    if (root == None):        return    inorder(root.left)    print(root.data, end = " ")    inorder(root.right) # Driver Codeif __name__ == '__main__':    root = newNode(10)    root.left = newNode(3)    root.right = newNode(10)    root.left.left = newNode(3)    root.left.right = newNode(1)    root.right.right = newNode(3)    root.right.right.left = newNode(3)    root.right.right.right = newNode(3)    deleteLeaves(root, 3)    print("Inorder traversal after deletion : ")    inorder(root) # This code is contributed by PranchalK
// C# code to delete all leaves with given// value.using System;     class GfG{     // A binary tree node    class Node    {        public int data;        public Node left, right;    }     // A utility function to allocate a new node    static Node newNode(int data)    {        Node newNode = new Node();        newNode.data = data;        newNode.left = null;        newNode.right = null;        return (newNode);    }     static Node deleteLeaves(Node root, int x)    {        if (root == null)            return null;        root.left = deleteLeaves(root.left, x);        root.right = deleteLeaves(root.right, x);         if (root.data == x &&            root.left == null &&            root.right == null)        {             return null;        }        return root;    }     static void inorder(Node root)    {        if (root == null)            return;        inorder(root.left);        Console.Write(root.data + " ");        inorder(root.right);    }     // Driver code    public static void Main(String[] args)    {        Node root = newNode(10);        root.left = newNode(3);        root.right = newNode(10);        root.left.left = newNode(3);        root.left.right = newNode(1);        root.right.right = newNode(3);        root.right.right.left = newNode(3);        root.right.right.right = newNode(3);        deleteLeaves(root, 3);        Console.Write("Inorder traversal after deletion : ");        inorder(root);    }} // This code is contributed by PrinciRaj1992
<script>     // JavaScript code to delete all leaves with given value.         class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }     // A utility function to allocate a new node    function newNode(data)    {        let newNode = new Node(data);        return (newNode);    }     function deleteLeaves(root, x)    {        if (root == null)            return null;        root.left = deleteLeaves(root.left, x);        root.right = deleteLeaves(root.right, x);         if (root.data == x && root.left == null && root.right == null)        {             return null;        }        return root;    }     function inorder(root)    {        if (root == null)            return;        inorder(root.left);        document.write(root.data + " "        inorder(root.right);    }         let root = newNode(10);    root.left = newNode(3);    root.right = newNode(10);    root.left.left = newNode(3);    root.left.right = newNode(1);    root.right.right = newNode(3);    root.right.right.left = newNode(3);    root.right.right.right = newNode(3);    deleteLeaves(root, 3);    document.write("Inorder traversal after deletion : ");    inorder(root); </script>
Output:  
Inorder traversal after deletion : 3 1 10 10
 
Delete leaf nodes with value as x | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersDelete leaf nodes with value as x | 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 / 3:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=qasFZ118RTk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
prerna saini
princiraj1992
PranchalKatiyar
simran_gujrati
rameshtravel07
tree-traversal
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.