Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Binary Tree to Binary Search Tree Conversion
Next article icon

Convert given binary tree to a XOR tree

Last Updated : 09 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Tree where each node has a value of either 0 or 1, the task is to convert the given Binary tree to an XOR tree i.e a tree such that each node value is the logical XOR between its children.

Note: Leaf nodes and nodes with one child are not considered as they don’t have both children.

Examples:

Input:
            1
         /    \
      1       0
    /  \     /  \
  0   1   0    1
Output:
            0
         /   \
       1      1
    /  \    /  \
 0    1  0    1
Explanation: Each node value is the Logical XOR of its children.
For example, the right most node in 2nd level is the Logical XOR of its children. i.e., 0 ^ 1 = 1  

Input:
           1
        /   \
      0      0
   /   \    /  
 1    0  1   
Output:
           1
       /     \
    1        0
   /  \     /  
 1    0  1 
 Explanation: Each node has value same as the Logical XOR of its children.
 For example, the left most node in 2nd level is the Logical Xor of its children. i.e., 1 ^ 0 = 1.
The rightmost child of second level has value unchanged because it has only one child.

 

Approach: The problem can be solved based on the following idea:

The idea is to perform a postorder traversal of the tree because in postorder traversal both the children are visited before the root node. During the traversal keep on performing the XOR of the children and change the value of the current node as per that.

Follow the steps to solve the problem:

  • For each node recursively check for the children of the nodes.
  • If the node has only one child or no child then do nothing. 
  • Else if the node has both children, then simply update the node’s data with the logical XOR of its children.

Below is the implementation of the above approach:  

C++




// C++ program to convert a BT to XOR tree
 
#include <bits/stdc++.h>
using namespace std;
 
// Struct node of binary tree
struct Node {
    int data;
    Node *left, *right;
};
 
// Function to create a new node
Node* newNode(int key)
{
    Node* node = new Node;
    node->data = key;
    node->left = node->right = NULL;
    return node;
}
 
// Utility function that converts
// BT to XOR tree which holds
// logical XOR property.
void convertTree(Node* root)
{
    // Base case
    if (root == NULL)
        return;
 
    // Recursion for left subtree
    convertTree(root->left);
 
    // Recursion for right subtree
    convertTree(root->right);
 
    // If the node has both childrens
    // then update node's data as
    // Logical Xor between childrens.
    if (root->left != NULL
        && root->right != NULL)
        root->data = root->left->data
                     ^ root->right->data;
}
 
// Function to print
void printInorder(Node* root)
{
    if (root == NULL)
        return;
 
    // Recursion for left subtree
    printInorder(root->left);
 
    // Print the data
    cout << root->data << " ";
 
    // Now recursion for right subtree
    printInorder(root->right);
}
 
// Driver code
int main()
{
    // Create a binary tree
    Node* root = newNode(1);
    root->left = newNode(1);
    root->right = newNode(0);
    root->left->left = newNode(0);
    root->left->right = newNode(1);
    root->right->left = newNode(0);
    root->right->right = newNode(1);
 
    cout << "Before conversion: ";
    printInorder(root);
 
    // Function to convert the tree
    convertTree(root);
    cout << "\nAfter conversion: ";
    printInorder(root);
    return 0;
}
 
 

Java




// JAVA program to convert a BT to XOR tree
import java.util.*;
class GFG
{
 
  // Struct node of binary tree
  public static class Node {
    int data;
    Node left, right;
  }
 
  // Function to create a new node
  public static Node newNode(int key)
  {
    Node node = new Node();
    node.data = key;
    node.left = node.right = null;
    return node;
  }
 
  // Utility function that converts
  // BT to XOR tree which holds
  // logical XOR property.
  public static void convertTree(Node root)
  {
    // Base case
    if (root == null)
      return;
 
    // Recursion for left subtree
    convertTree(root.left);
 
    // Recursion for right subtree
    convertTree(root.right);
 
    // If the node has both childrens
    // then update node's data as
    // Logical Xor between childrens.
    if (root.left != null && root.right != null)
      root.data = root.left.data ^ root.right.data;
  }
 
  // Function to print
  public static void printInorder(Node root)
  {
    if (root == null)
      return;
 
    // Recursion for left subtree
    printInorder(root.left);
 
    // Print the data
    System.out.print(root.data + " ");
 
    // Now recursion for right subtree
    printInorder(root.right);
  }
 
  // Driver code
  public static void main(String[] args)
  {
    // Create a binary tree
    Node root = newNode(1);
    root.left = newNode(1);
    root.right = newNode(0);
    root.left.left = newNode(0);
    root.left.right = newNode(1);
    root.right.left = newNode(0);
    root.right.right = newNode(1);
 
    System.out.print("Before conversion: ");
    printInorder(root);
 
    // Function to convert the tree
    convertTree(root);
    System.out.print("\nAfter conversion: ");
    printInorder(root);
  }
}
 
// This code is contributed by Taranpreet
 
 

Python3




# Python program for the above approach
 
# Struct node of binary tree
class Node:
    def __init__(self,key):
        self.data = key
        self.left = None
        self.right = None
 
# Utility function that converts
# BT to XOR tree which holds
# logical XOR property.
def convertTree(root):
    # Base case
    if (root == None):
        return
 
    # Recursion for left subtree
    convertTree(root.left)
 
    # Recursion for right subtree
    convertTree(root.right)
 
    # If the node has both childrens
    # then update node's data as
    # Logical Xor between childrens.
    if (root.left != None and root.right != None):
        root.data = root.left.data ^ root.right.data
 
# Function to print
def printInorder(root):
             
    if (root == None):
        return
 
    # Recursion for left subtree
    printInorder(root.left)
 
    # Print the data
    print(root.data ,end =  " ")
 
    # Now recursion for right subtree
    printInorder(root.right)
 
# Driver code
 
# Create a binary tree
root = Node(1)
root.left = Node(1)
root.right = Node(0)
root.left.left = Node(0)
root.left.right = Node(1)
root.right.left = Node(0)
root.right.right = Node(1)
 
print("Before conversion:",end=" ")
printInorder(root)
 
# Function to convert the tree
convertTree(root)
print()
print("After conversion:",end=" ")
printInorder(root)
 
# This code is contributed by shinjanpatra
 
 

C#




using System;
 
// C# program to convert a BT to XOR tree
public class GFG
{
 
  // Struct node of binary tree
  public class Node {
    public int data;
    public Node left, right;
  }
 
  // Function to create a new node
  public static Node newNode(int key)
  {
    Node node = new Node();
    node.data = key;
    node.left = node.right = null;
    return node;
  }
 
  // Utility function that converts
  // BT to XOR tree which holds
  // logical XOR property.
  public static void convertTree(Node root)
  {
    // Base case
    if (root == null)
      return;
 
    // Recursion for left subtree
    convertTree(root.left);
 
    // Recursion for right subtree
    convertTree(root.right);
 
    // If the node has both childrens
    // then update node's data as
    // Logical Xor between childrens.
    if (root.left != null && root.right != null)
      root.data = root.left.data ^ root.right.data;
  }
 
  // Function to print
  public static void printInorder(Node root)
  {
    if (root == null)
      return;
 
    // Recursion for left subtree
    printInorder(root.left);
 
    // Print the data
    Console.Write(root.data + " ");
 
    // Now recursion for right subtree
    printInorder(root.right);
  }
 
  // Driver code
  public static void Main(string[] args)
  {
    // Create a binary tree
    Node root = newNode(1);
    root.left = newNode(1);
    root.right = newNode(0);
    root.left.left = newNode(0);
    root.left.right = newNode(1);
    root.right.left = newNode(0);
    root.right.right = newNode(1);
 
    Console.Write("Before conversion: ");
    printInorder(root);
 
    // Function to convert the tree
    convertTree(root);
    Console.Write("\nAfter conversion: ");
    printInorder(root);
  }
}
 
// This code is contributed by jana_sayantan.
 
 

Javascript




<script>
        // JavaScript code for the above approach
 
        // Struct node of binary tree
        class Node {
            constructor(key) {
                this.data = key;
                this.left = null;
                this.right = null;
            }
        };
 
        // Utility function that converts
        // BT to XOR tree which holds
        // logical XOR property.
        function convertTree(root) {
            // Base case
            if (root == null)
                return;
 
            // Recursion for left subtree
            convertTree(root.left);
 
            // Recursion for right subtree
            convertTree(root.right);
 
            // If the node has both childrens
            // then update node's data as
            // Logical Xor between childrens.
            if (root.left != null
                && root.right != null)
                root.data = root.left.data
                    ^ root.right.data;
        }
 
        // Function to print
        function printInorder(root) {
            if (root == null)
                return;
 
            // Recursion for left subtree
            printInorder(root.left);
 
            // Print the data
            document.write(root.data + " ");
 
            // Now recursion for right subtree
            printInorder(root.right);
        }
 
        // Driver code
 
        // Create a binary tree
        let root = new Node(1);
        root.left = new Node(1);
        root.right = new Node(0);
        root.left.left = new Node(0);
        root.left.right = new Node(1);
        root.right.left = new Node(0);
        root.right.right = new Node(1);
 
        document.write("Before conversion: ");
        printInorder(root);
 
        // Function to convert the tree
        convertTree(root);
        document.write('<br>' + "After conversion: ");
        printInorder(root);
 
    // This code is contributed by Potta Lokesh
    </script>
 
 
Output
Before conversion: 0 1 1 1 0 0 1  After conversion: 0 1 1 0 0 1 1 

Time Complexity: O(N)
Auxiliary Space: O(N)



Next Article
Binary Tree to Binary Search Tree Conversion

U

upendra200223
Improve
Article Tags :
  • DSA
  • Recursion
  • Tree
  • Binary Tree
  • PostOrder Traversal
Practice Tags :
  • Recursion
  • Tree

Similar Reads

  • Convert a given tree to its Sum Tree
    Given a Binary Tree where each node has positive and negative values. Convert this to a tree where each node contains the sum of the left and right sub trees in the original tree. The values of leaf nodes are changed to 0. For example, the following tree 10 / \ -2 6 / \ / \ 8 -4 7 5 should be change
    15+ min read
  • Binary Tree to Binary Search Tree Conversion
    Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree. Examples Input: Output: Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of B
    7 min read
  • Count of subtrees in a Binary Tree having XOR value K
    Given a value K and a binary tree, the task is to find out number of subtrees having XOR of all its elements equal to K.Examples: Input K = 5, Tree = 2 / \ 1 9 / \ 10 5Output: 2Explanation:Subtree 1: 5It has only one element i.e. 5.So XOR of subtree = 5Subtree 1: 2 / \ 1 9 / \ 10 5It has elements 2,
    14 min read
  • Invert Binary Tree - Change to Mirror Tree
    Given a binary tree, the task is to convert the binary tree to its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Example 1: Explanation: In the inverted tree, every non-leaf node has its left and right child interc
    15 min read
  • Construct a Perfect Binary Tree with given Height
    Given an integer N, the task is to generate a perfect binary tree with height N such that each node has a value that is the same as its depth. Return the inorder traversal of the generated binary tree. A Perfect binary tree is a type of binary tree where every internal node has exactly two child nod
    9 min read
  • Trim given Binary Tree for any subtree containing only 0s
    Given a Binary tree, the task is to trim this tree for any subtree containing only 0s. Examples: Input: 1 \ 0 / \ 0 1 Output: 1 \ 0 \ 1 Explanation: The subtree shown as bold below does not contain any 1. Hence it can be trimmed. 1 \ 0 / \ 0 1 Input: 1 / \ 1 0 / \ / \ 1 1 0 1 / 0 Output: 1 / \ 1 0 /
    7 min read
  • Construct XOR tree by Given leaf nodes of Perfect Binary Tree
    Given the leaf nodes of a perfect binary tree, the task is to construct the XOR tree and print the root node of this tree. An XOR tree is a tree whose parent node is the XOR of the left child and the right child node of the tree. Parent node = Left child node ^ Right child node Examples: Input: arr
    12 min read
  • Check if the given n-ary tree is a binary tree
    Given an n-ary tree consisting of n nodes, the task is to check whether the given tree is binary or not.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-ary tree allows for multip
    6 min read
  • Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
    Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. Following diagram sh
    12 min read
  • Closest leaf to a given node in Binary Tree
    Given a Binary Tree and a node x in it, find distance of the closest leaf to x in Binary Tree. If given node itself is a leaf, then distance is 0.Examples: Input: Root of below tree And x = pointer to node 13 10 / \ 12 13 / 14 Output 1 Distance 1. Closest leaf is 14. Input: Root of below tree And x
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences