Convert a binary tree to a tree with the logical XOR property

Updated

You have given a Binary Tree with each node having value either 0 or 1. And the task is to convert the given Binary tree to a tree that holds Logical XOR property, which means that each and every node value must be the logical XOR between its children.

Example :

Input :
       1
     /   \
    1      0
  /  \    /  \
 0    1  1    0
Output : 0 1 1 0 1 1 0

Explanation :

Given Tree
       1
     /   \
    1      0
  /  \    /  \
 0    1  1    0

After Processing (Xoring)
       0
     /   \
    1      1
  /  \    /  \
 0    1  1    0

Approach :

Basic idea used is to traverse given binary tree in postorder fashion.

Step 1: Recursively check each and every node.

Step 2: If node contains only one children then its value will be the same as the child.

Step 3: If node contains its both child then its value will be equal to  the logic XOR of its child data.

Step 4: Resultant Binary tree will be holds the Logical XOR property.

Implementation :

# Python program to convert a
# given binary tree to
# a tree that holds
# logical XOR property.

# Function that allocates a new


class newNode:

    # Construct to create a new node
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

# Convert the given tree
# to a tree where each node
# is logical xor of its children
# The main idea is to do
# Postorder traversal


def convertTree(root):

    if (root == None):
        return

    # First recur on left child
    convertTree(root.left)

    # Then recur on right child
    convertTree(root.right)

    if (root.left and root.right):
        root.data = ((root.left.data) ^ (root.right.data))


def printInorder(root):

    if (root == None):
        return

    # First recur on left child
    printInorder(root.left)

    # Then print the data of node
    print(root.data, end=" ")

    # Now recur on right child
    printInorder(root.right)


# Driver Code
if __name__ == '__main__':

    root = newNode(0)
    root.left = newNode(1)
    root.right = newNode(0)
    root.left.left = newNode(0)
    root.left.right = newNode(0)
    root.right.left = newNode(1)
    root.right.right = newNode(0)

    convertTree(root)
    printInorder(root)

Output :

0 0 0 1 1 1 0
Comment
Mithlesh Upadhyay Published 27 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials