Convert a given Binary tree to a tree that holds Logical AND property | C ++ code to convert a given binary tree to a tree that holds logical AND property . ; Structure of binary tree ; function to create a new node ; Convert the given tree to a tree where each node is logical AND of its children The main idea is to do Postorder traversal ; first recur on left child ; then recur on right child ; first recur on left child ; then print the data of node ; now recur on right child ; main function ; Create following Binary Tree 1 / \ 1 0 / \ / \ 0 1 1 1
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int key ) { struct Node * node = new Node ; node -> data = key ; node -> left = node -> right = NULL ; return node ; } void convertTree ( Node * root ) { if ( root == NULL ) return ; convertTree ( root -> left ) ; convertTree ( root -> right ) ; if ( root -> left != NULL && root -> right != NULL ) root -> data = ( root -> left -> data ) & ( root -> right -> data ) ; } void printInorder ( Node * root ) { if ( root == NULL ) return ; printInorder ( root -> left ) ; printf ( " % d ▁ " , root -> data ) ; printInorder ( root -> right ) ; } int main ( ) { Node * root = newNode ( 0 ) ; root -> left = newNode ( 1 ) ; root -> right = newNode ( 0 ) ; root -> left -> left = newNode ( 0 ) ; root -> left -> right = newNode ( 1 ) ; root -> right -> left = newNode ( 1 ) ; root -> right -> right = newNode ( 1 ) ; printf ( " Inorder traversal before conversion " printInorder ( root ) ; convertTree ( root ) ; printf ( " Inorder traversal after conversion " printInorder ( root ) ; return 0 ; }