Given a Binary Tree, the task is to remove the leaf nodes of the Binary Tree during each operation and print the count.
Examples:
Input:
Output: 4 2 1 1
Explanation:
In the 1st operation removing the leaf nodes { 1, 3, 4, 6 } from the binary tree.
In the 2nd operation removing the leaf nodes { 8, 7 }
In the 3rd operation removing the leaf nodes { 5 }
In the 4th operation removing the leaf nodes { 1 }
Therefore, the count of leaf nodes removed in each operation 4 2 1 1.
Input:
Output: 2 1
Naive Approach: The simplest approach to solve this problem to repeatedly traverse the tree for each operation and print the count of leaf nodes currently present in the binary tree and delete all the leaf nodes from the binary tree.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to observe that, a node is not deleted unless both its children have been deleted already. Therefore, it can be determined that on which step a node will be deleted, which will be equal to 1 + maximum path length from that node to any leaf node in the subtree rooted at that node. Follow the steps below to solve this problem:
- Initialize a Map, say M, to store the leaf nodes at each deletion from the tree.
- Perform a DFS Traversal on the given Binary Tree following the steps below:
- Check if the given node is NULL or not. If found to be true, then return 0.
- Otherwise, recursively call for left and right nodes and store the values returned from it.
- Find the maximum height, say maxHeight, when each node will be a leaf node as (1 + maximum of the values returned by the left and right recursive calls) in the above steps for each node.
- Insert the current node in the Map M at key maxHeight.
- After completing the above steps, print the count of leaf nodes stored in the Map after each deletion.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Structure of a// Binary Tree Nodestruct Node { int data; Node *left, *right;};// Function to allocate// a new tree nodeNode* newNode(int data){ Node* node = new Node; node->data = data; node->left = NULL; node->right = NULL; return node;}// Function to find the maximum height// from leaf in the subtree rooted at// current node and add that to hashmapint maxHeightToLeafUTIL( Node* curr, map<int, vector<int> >& mp){ if (curr == NULL) { return 0; } // Max height to leaf in left subtree int leftLeaf = maxHeightToLeafUTIL(curr->left, mp); // Max height to leaf in right subtree int rightLeaf = maxHeightToLeafUTIL(curr->right, mp); // Max height to leaf in current subtree int maxHeightSubtree = 1 + max(leftLeaf, rightLeaf); // Adding current node to the Map mp[maxHeightSubtree].push_back( curr->data); return maxHeightSubtree;}// Function to find the count of leaf nodes// by repeatedly removing the leaf nodesvoid printAndDelete(Node* root){ // Stores the leaf deletion with // each iteration map<int, vector<int> > mp; // Function Call to find the order // of deletion of nodes maxHeightToLeafUTIL(root, mp); // Printing the map values for (auto step : mp) { cout << mp[step.first].size() << " "; }}// Driver codeint main(){ // Given Binary Tree Node* root = newNode(2); root->right = newNode(7); root->right->right = newNode(6); root->left = newNode(5); root->left->left = newNode(1); root->left->right = newNode(8); root->left->right->left = newNode(3); root->left->right->right = newNode(4); /* Input : 2 / \ 5 7 / \ \ 1 8 6 / \ 3 4*/ // Function Call printAndDelete(root); return 0;} |
Python3
# Python3 program for the above approach # Tree node structure used in the programclass Node: def __init__(self, x): self.data = x self.left = None self.right = None# Function to find the maximum height# from leaf in the subtree rooted at# current node and add that to hashmapdef maxHeightToLeafUTIL(curr): global mp if (curr == None): return 0 # Max height to leaf in left subtree leftLeaf = maxHeightToLeafUTIL(curr.left) # Max height to leaf in right subtree rightLeaf = maxHeightToLeafUTIL(curr.right) # Max height to leaf in current subtree maxHeightSubtree = 1 + max(leftLeaf, rightLeaf) # Adding current node to the Map mp[maxHeightSubtree].append(curr.data) return maxHeightSubtree# Function to find the count of leaf nodes# by repeatedly removing the leaf nodesdef printAndDelete(root): global mp # Function Call to find the order # of deletion of nodes maxHeightToLeafUTIL(root) for step in mp: if len(step): print(len(step), end = " ")# Driver codeif __name__ == '__main__': mp = [[] for i in range(1000)] # Given Binary Tree root = Node(2) root.right = Node(7) root.right.right = Node(6) root.left = Node(5) root.left.left = Node(1) root.left.right = Node(8) root.left.right.left = Node(3) root.left.right.right = Node(4) # # # Input : # 2 # / \ # 5 7 # / \ \ # 1 8 6 # / \ # 3 4 # Function Call printAndDelete(root) # This code is contributed by mohit kumar 29 |
4 2 1 1
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Print the longest leaf to leaf path in a Binary tree
- Step by Step guide to Write your own WordPress Template
- Program to count leaf nodes in a binary tree
- Count Non-Leaf nodes in a Binary Tree
- Count root to leaf paths having exactly K distinct nodes in a Binary Tree
- Count pairs of leaf nodes in a Binary Tree which are at most K distance apart
- Iterative program to count leaf nodes in a Binary Tree
- Maximum sum of leaf nodes among all levels of the given binary tree
- Find K smallest leaf nodes from a given Binary Tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Mimimum number of leaves required to be removed from a Tree to satisfy the given condition
- Sum of indices of Characters removed to obtain an Empty String based on given conditions
- Remove all leaf nodes from a Generic Tree or N-ary Tree
- Minimum number of Nodes to be removed such that no subtree has more than K nodes
- Pairwise Swap leaf nodes in a binary tree
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Product of all leaf nodes of binary tree
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print the nodes of binary tree as they become the leaf node
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : mohit kumar 29



