Print all the root-to-leaf paths of a Binary Tree whose XOR is non-zero
Last Updated :
23 Jan, 2023
Given a Binary Tree, the task is to print all root-to-leaf paths of this tree whose xor value is non-zero.
Examples:
Input:
10
/ \
10 3
/ \
10 3
/ \ / \
7 3 42 13
/
7
Output:
10 3 10 7
10 3 3 42
Explanation:
All the paths in the given binary tree are :
{10, 10} xor value of the path is
= 10 ^ 10 = 0
{10, 3, 10, 7} xor value of the path is
= 10 ^ 3 ^ 10 ^ 7 != 0
{10, 3, 3, 42} xor value of the path is
= 10 ^ 3 ^ 3 ^ 42 != 0
{10, 3, 10, 3} xor value of the path is
= 10 ^ 3 ^ 10 ^ 3 = 0
{10, 3, 3, 13, 7} xor value of the path is
= 10 ^ 3 ^ 3 ^ 13 ^ 7 = 0.
Hence, {10, 3, 10, 7} and {10, 3, 3, 42} are
the paths whose xor value is non-zero.
Input:
5
/ \
21 77
/ \ \
5 21 16
\ /
5 3
Output :
5 21 5
5 77 16 3
Explanation:
{5, 21, 5} and {5, 77, 16, 3} are the paths
whose xor value is non-zero.
Approach:
To solve the problem mentioned above the main idea is to traverse the tree and check if the xor of all the elements in that path is zero or not.
- We need to traverse the tree recursively using Pre-Order Traversal.
- For each node keep calculating the XOR of the path from root till the current node.
- If the node is a leaf node that is left and the right child for the current nodes are NULL then we check if the xor value of the path is non-zero or not, if it is then we print the entire path.
Below is the implementation of the above approach:
C++
// C++ program to Print all the Paths of a
// Binary Tree whose XOR gives a non-zero value
#include <bits/stdc++.h>
using namespace std;
// A Tree node
struct Node {
int key;
struct Node *left, *right;
};
// Function to create a new node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
// Function to check whether Path
// is has non-zero xor value or not
bool PathXor(vector<int>& path)
{
int ans = 0;
// Iterating through the array
// to find the xor value
for (auto x : path) {
ans ^= x;
}
return (ans != 0);
}
// Function to print a path
void printPaths(vector<int>& path)
{
for (auto x : path) {
cout << x << " ";
}
cout << endl;
}
// Function to find the paths of
// binary tree having non-zero xor value
void findPaths(struct Node* root,
vector<int>& path)
{
// Base case
if (root == NULL)
return;
// Store the value in path vector
path.push_back(root->key);
// Recursively call for left sub tree
findPaths(root->left, path);
// Recursively call for right sub tree
findPaths(root->right, path);
// Condition to check, if leaf node
if (root->left == NULL
&& root->right == NULL) {
// Condition to check,
// if path has non-zero xor or not
if (PathXor(path)) {
// Print the path
printPaths(path);
}
}
// Remove the last element
// from the path vector
path.pop_back();
}
// Function to find the paths
// having non-zero xor value
void printPaths(struct Node* node)
{
vector<int> path;
findPaths(node, path);
}
// Driver Code
int main()
{
/* 10
/ \
10 3
/ \
10 3
/ \ / \
7 3 42 13
/
7
*/
// Create Binary Tree as shown
Node* root = newNode(10);
root->left = newNode(10);
root->right = newNode(3);
root->right->left = newNode(10);
root->right->right = newNode(3);
root->right->left->left = newNode(7);
root->right->left->right = newNode(3);
root->right->right->left = newNode(42);
root->right->right->right = newNode(13);
root->right->right->right->left = newNode(7);
// Print non-zero XOR Paths
printPaths(root);
return 0;
}
Java
// Java program to Print all the Paths of a
// Binary Tree whose XOR gives a non-zero value
import java.util.*;
class GFG{
// A Tree node
static class Node
{
int key;
Node left, right;
};
// Function to create a new node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null;
return (temp);
}
// Function to check whether Path
// is has non-zero xor value or not
static boolean PathXor(Vector<Integer> path)
{
int ans = 0;
// Iterating through the array
// to find the xor value
for (int x : path)
{
ans ^= x;
}
return (ans != 0);
}
// Function to print a path
static void printPaths(Vector<Integer> path)
{
for (int x : path)
{
System.out.print(x + " ");
}
System.out.println();
}
// Function to find the paths of
// binary tree having non-zero xor value
static void findPaths(Node root,
Vector<Integer> path)
{
// Base case
if (root == null)
return;
// Store the value in path vector
path.add(root.key);
// Recursively call for left sub tree
findPaths(root.left, path);
// Recursively call for right sub tree
findPaths(root.right, path);
// Condition to check, if leaf node
if (root.left == null &&
root.right == null)
{
// Condition to check,
// if path has non-zero xor or not
if (PathXor(path))
{
// Print the path
printPaths(path);
}
}
// Remove the last element
// from the path vector
path.remove(path.size() - 1);
}
// Function to find the paths
// having non-zero xor value
static void printPaths(Node node)
{
Vector<Integer> path = new Vector<Integer>();
findPaths(node, path);
}
// Driver Code
public static void main(String[] args)
{
/* 10
/ \
10 3
/ \
10 3
/ \ / \
7 3 42 13
/
7
*/
// Create Binary Tree as shown
Node root = newNode(10);
root.left = newNode(10);
root.right = newNode(3);
root.right.left = newNode(10);
root.right.right = newNode(3);
root.right.left.left = newNode(7);
root.right.left.right = newNode(3);
root.right.right.left = newNode(42);
root.right.right.right = newNode(13);
root.right.right.right.left = newNode(7);
// Print non-zero XOR Paths
printPaths(root);
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 program to print all
# the paths of a Binary Tree
# whose XOR gives a non-zero value
# A Tree node
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Function to check whether Path
# is has non-zero xor value or not
def PathXor(path: list) -> bool:
ans = 0
# Iterating through the array
# to find the xor value
for x in path:
ans ^= x
return (ans != 0)
# Function to print a path
def printPathsList(path: list) -> None:
for x in path:
print(x, end = " ")
print()
# Function to find the paths of
# binary tree having non-zero xor value
def findPaths(root: Node, path: list) -> None:
# Base case
if (root == None):
return
# Store the value in path vector
path.append(root.key)
# Recursively call for left sub tree
findPaths(root.left, path)
# Recursively call for right sub tree
findPaths(root.right, path)
# Condition to check, if leaf node
if (root.left == None and
root.right == None):
# Condition to check, if path
# has non-zero xor or not
if (PathXor(path)):
# Print the path
printPathsList(path)
# Remove the last element
# from the path vector
path.pop()
# Function to find the paths
# having non-zero xor value
def printPaths(node: Node) -> None:
path = []
newNode = node
findPaths(newNode, path)
# Driver Code
if __name__ == "__main__":
''' 10
/ \
10 3
/ \
10 3
/ \ / \
7 3 42 13
/
7
'''
# Create Binary Tree as shown
root = Node(10)
root.left = Node(10)
root.right = Node(3)
root.right.left = Node(10)
root.right.right = Node(3)
root.right.left.left = Node(7)
root.right.left.right = Node(3)
root.right.right.left = Node(42)
root.right.right.right = Node(13)
root.right.right.right.left = Node(7)
# Print non-zero XOR Paths
printPaths(root)
# This code is contributed by sanjeev2552
C#
// C# program to Print all the Paths of a
// Binary Tree whose XOR gives a non-zero value
using System;
using System.Collections.Generic;
class GFG{
// A Tree node
class Node
{
public int key;
public Node left, right;
};
// Function to create a new node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null;
return (temp);
}
// Function to check whether Path
// is has non-zero xor value or not
static bool PathXor(List<int> path)
{
int ans = 0;
// Iterating through the array
// to find the xor value
foreach (int x in path)
{
ans ^= x;
}
return (ans != 0);
}
// Function to print a path
static void printPaths(List<int> path)
{
foreach (int x in path)
{
Console.Write(x + " ");
}
Console.WriteLine();
}
// Function to find the paths of
// binary tree having non-zero xor value
static void findPaths(Node root,
List<int> path)
{
// Base case
if (root == null)
return;
// Store the value in path vector
path.Add(root.key);
// Recursively call for left sub tree
findPaths(root.left, path);
// Recursively call for right sub tree
findPaths(root.right, path);
// Condition to check, if leaf node
if (root.left == null &&
root.right == null)
{
// Condition to check,
// if path has non-zero xor or not
if (PathXor(path))
{
// Print the path
printPaths(path);
}
}
// Remove the last element
// from the path vector
path.RemoveAt(path.Count - 1);
}
// Function to find the paths
// having non-zero xor value
static void printPaths(Node node)
{
List<int> path = new List<int>();
findPaths(node, path);
}
// Driver Code
public static void Main(String[] args)
{
/* 10
/ \
10 3
/ \
10 3
/ \ / \
7 3 42 13
/
7
*/
// Create Binary Tree as shown
Node root = newNode(10);
root.left = newNode(10);
root.right = newNode(3);
root.right.left = newNode(10);
root.right.right = newNode(3);
root.right.left.left = newNode(7);
root.right.left.right = newNode(3);
root.right.right.left = newNode(42);
root.right.right.right = newNode(13);
root.right.right.right.left = newNode(7);
// Print non-zero XOR Paths
printPaths(root);
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// JavaScript program to Print all the Paths of a
// Binary Tree whose XOR gives a non-zero value
// A Tree node
class Node
{
constructor(key) {
this.left = null;
this.right = null;
this.key = key;
}
}
// Function to create a new node
function newNode(key)
{
let temp = new Node(key);
return (temp);
}
// Function to check whether Path
// is has non-zero xor value or not
function PathXor(path)
{
let ans = 0;
// Iterating through the array
// to find the xor value
for (let x = 0; x < path.length; x++)
{
ans ^= path[x];
}
if(ans != 0)
{
return true;
}
else{
return false;
}
}
// Function to print a path
function printPaths(path)
{
for (let x = 0; x < path.length; x++)
{
document.write(path[x] + " ");
}
document.write("</br>");
}
// Function to find the paths of
// binary tree having non-zero xor value
function findPaths(root, path)
{
// Base case
if (root == null)
return;
// Store the value in path vector
path.push(root.key);
// Recursively call for left sub tree
findPaths(root.left, path);
// Recursively call for right sub tree
findPaths(root.right, path);
// Condition to check, if leaf node
if (root.left == null &&
root.right == null)
{
// Condition to check,
// if path has non-zero xor or not
if (PathXor(path))
{
// Print the path
printPaths(path);
}
}
// Remove the last element
// from the path vector
path.pop();
}
// Function to find the paths
// having non-zero xor value
function printpaths(node)
{
let path = [];
findPaths(node, path);
}
/* 10
/ \
10 3
/ \
10 3
/ \ / \
7 3 42 13
/
7
*/
// Create Binary Tree as shown
let root = newNode(10);
root.left = newNode(10);
root.right = newNode(3);
root.right.left = newNode(10);
root.right.right = newNode(3);
root.right.left.left = newNode(7);
root.right.left.right = newNode(3);
root.right.right.left = newNode(42);
root.right.right.right = newNode(13);
root.right.right.right.left = newNode(7);
// Print non-zero XOR Paths
printpaths(root);
</script>
Output: 10 3 10 7
10 3 3 42
Time complexity: O(N) where N is no of nodes in given binary tree
Space Complexity: O(h) where h is the height of the binary tree.
Similar Reads
Print Root-to-Leaf Paths in a Binary Tree
Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the leaf nodes of the binary tree.Example:Input:Output: 1 2 41 2 51 3 Using Recursion - O(n) Time and O(h) SpaceIn the recursive approach to print all paths from the root to leaf nodes, we can perform
2 min read
Find all root to leaf path sum of a Binary Tree
Given a Binary Tree, the task is to print all the root to leaf path sum of the given Binary Tree. Examples: Input: 30 / \ 10 50 / \ / \ 3 16 40 60 Output: 43 56 120 140 Explanation: In the above binary tree there are 4 leaf nodes. Hence, total 4 path sum are present from root node to the leaf node.
8 min read
Print path from root to all nodes in a Complete Binary Tree
Given a number N which is the total number of nodes in a complete binary tree where nodes are number from 1 to N sequentially level-wise. The task is to write a program to print paths from root to all of the nodes in the Complete Binary Tree.For N = 3, the tree will be: 1 / \ 2 3 For N = 7, the tree
9 min read
Print the first shortest root to leaf path in a Binary Tree
Given a Binary Tree with distinct values, the task is to find the first smallest root to leaf path. We basically need to find the leftmost root to leaf path that has the minimum number of nodes.The root to leaf path in below image is 1-> 3 which is the leftmost root to leaf path that has the mini
8 min read
Count of root to leaf paths whose permutation is palindrome in a Binary Tree
Given a binary tree where node contains characters, the task is to count the number of paths from root vertex to leaf such that at least one permutation of the node values in the path is a palindrome.Examples: Input: 2 / \ 3 1 / \ \ 3 4 2 / \ / \ 2 1 2 1 Output: 2 Explanation: Paths whose one of the
7 min read
Count the number of paths from root to leaf of a Binary tree with given XOR value
Given a value K and a binary tree, we have to find out the total number of paths from the root to leaf nodes having XOR of all its nodes along the path equal to K.Examples: Input: K = 6 2 / \ 1 4 / \ 10 5 Output: 2 Explanation: Subtree 1: 2 \ 4 This particular path has 2 nodes, 2 and 4 and (2 xor 4)
8 min read
Print the longest leaf to leaf path in a Binary tree
C++ // C++ program to print the longest leaf to leaf // path #include <bits/stdc++.h> using namespace std; // Tree node structure used in the program struct Node { int data; Node *left, *right; }; struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->lef
15+ min read
Print Root-to-Leaf Paths in a Binary Tree Using Recursion
Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the leaf nodes of the binary tree.Note: The paths should be returned such that paths from the left subtree of any node are listed first, followed by paths from the right subtree.Example:Input: root[] =
6 min read
Print all the paths from root, with a specified sum in Binary tree
Given a Binary tree and a sum, the task is to return all the paths, starting from root, that sums upto the given sum.Note: This problem is different from root to leaf paths. Here path doesn't need to end on a leaf node.Examples: Input: Output: [[1, 3, 4]]Explanation: The below image shows the path s
8 min read
Print all leaf nodes of a binary tree from right to left
Given a binary tree, the task is to print all the leaf nodes of the binary tree from right to left. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 7 6 5 4 Input : 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 Output : 9 8 7 4 Recursive Approach: Traverse the tree in Preorder fashion, by first processing t
14 min read