Delete leaf nodes with value k in C++ program

In this tutorial, we are going to learn how to delete the leaf nodes from a tree with the given value.

Let's see the steps to solve the problem.

  • Write a struct Node for a binary tree.

  • Write a function to traverse (inorder, preorder, postorder) through the tree and print all data.

  • Initialize the tree by creating nodes with the struct.

  • Initialize the x value.

  • Write a function to delete the leaf nodes with the given value. It accepts two arguments root node and k value.

    • If the root is a null return.

    • Replace the left node of the root with a new root after deletion.

    • Same with the right node of the root.

    • If the current root node data is equal to k and it is a leaf node, then return a null pointer.

    • Return root node


Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node *left, *right;
struct Node* newNode(int data) {
   struct Node* newNode = new Node;
   newNode->data = data;
   newNode->left = newNode->right = NULL;
   return newNode;
Node* deleteLeafNodes(Node* root, int k) {
   if (root == NULL) {
      return nullptr;
   root->left = deleteLeafNodes(root->left, k);
   root->right = deleteLeafNodes(root->right, k);
   // checking the current node data with k
   if (root->data == k && root->left == NULL && root->right == NULL) {
      // deleting the node
      return nullptr;
   return root;
void inorder(Node* root) {
   if (root == NULL) {
   cout << root->data << " ";
int main(void) {
   struct Node* root = newNode(1);
   root->left = newNode(2);
   root->right = newNode(3);
   root->left->left = newNode(3);
   root->left->right = newNode(4);
   root->right->right = newNode(5);
   root->right->left = newNode(4);
   root->right->right->left = newNode(4);
   root->right->right->right = newNode(4);
   deleteLeafNodes(root, 4);
   cout << "Tree: ";
   cout << endl;
   return 0;


If you execute the above code, then you will get the following result.

Tree: 3 2 1 3 5


If you have any queries in the tutorial, mention them in the comment section.