Remove all subtrees consisting only of even valued nodes from a Binary Tree | C ++ program for the above approach ; Node of the tree ; Function to create a new node ; Function to print tree level wise ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root ; Print front of queue and remove it from queue ; If left child is present ; Otherwise ; If right child is present ; Otherwise ; Function to remove subtrees ; Base Case ; Search for required condition in left and right half ; If the node is even and leaf node ; Driver Code ; Function Call ; Print answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; } ; node * newNode ( int key ) { node * temp = new node ; temp -> data = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } void printLevelOrder ( node * root ) { if ( ! root ) return ; queue < node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { node * temp = q . front ( ) ; cout << temp -> data << " ▁ " ; q . pop ( ) ; if ( temp -> left != NULL ) { q . push ( temp -> left ) ; } else if ( temp -> right != NULL ) { cout << " NULL ▁ " ; } if ( temp -> right != NULL ) { q . push ( temp -> right ) ; } else if ( temp -> left != NULL ) { cout << " NULL ▁ " ; } } } node * pruneTree ( node * root ) { if ( ! root ) { return NULL ; } root -> left = pruneTree ( root -> left ) ; root -> right = pruneTree ( root -> right ) ; if ( root -> data % 2 == 0 && ! root -> right && ! root -> left ) return NULL ; return root ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> left -> left = newNode ( 8 ) ; root -> left -> right = newNode ( 10 ) ; root -> right = newNode ( 7 ) ; root -> right -> left = newNode ( 12 ) ; root -> right -> right = newNode ( 5 ) ; node * newRoot = pruneTree ( root ) ; printLevelOrder ( newRoot ) ; return 0 ; }