Convert a given Binary tree to a tree that holds Logical AND property on C++

In this tutorial, we will be discussing a program to convert a given Binary tree to a tree that holds Logical AND property.

For this we will be provided with a binary tree. Our task is to convert it into a tree that holds the logical AND property means that a node has a value of the AND operation of its children nodes. Note that every node can have a value either zero or one.


 Live Demo

using namespace std;
//node structure of binary tree
struct Node{
   int data;
   struct Node* left;
   struct Node* right;
//creation of a new node
struct Node* newNode(int key){
   struct Node* node = new Node;
   node->data= key;
   node->left = node->right = NULL;
   return node;
//converting the tree with nodes following
//logical AND operation
void transform_tree(Node *root){
   if (root == NULL)
   //moving to first left node
   //moving to first right node
   if (root->left != NULL && root->right != NULL)
      root->data = (root->left->data) &
//printing the inorder traversal
void print_tree(Node* root){
   if (root == NULL)
   printf("%d ", root->data);
int main(){
   Node *root=newNode(0);
   printf("Before conversion :\n");
   printf("\nAfter conversion :\n");
   return 0;


Before conversion :
0 1 1 0 1 0 1
After conversion :
0 0 1 0 1 1 1

Updated on: 06-Jan-2020


Kickstart Your Career

Get certified by completing the course

Get Started