Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Example
Let's see the code.
#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) {
return;
}
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
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: ";
inorder(root);
cout << endl;
return 0;
}
Output
If you execute the above code, then you will get the following result.
Tree: 3 2 1 3 5
Conclusion
If you have any queries in the tutorial, mention them in the comment section.