Maximum XOR with given value in the path from root to given node in the tree

Given a tree with N distinct nodes from the range [1, n] and two integers x and val. The task is to find the maximum value of any node when XORed with x on the path from the root to val.
Examples:Â
Input: val = 6, x = 4
1
/ \
2 3
/ \
4 5
/
6
Output: 7
the path is 1 -> 3 -> 5 -> 6
1 ^ 4 = 5
3 ^ 4 = 7
5 ^ 4 = 1
6 ^ 4 = 2
Maximum is 7
Input: val = 4, x = 1
1
/ \
2 3
/
4
Output: 5
Approach:Â Â
- An optimized solution to the problem is to create a parent array to store the parent of each of the node.
- Start from the given node and keep on going up in the tree using the parent array (this will be helpful when answering a number of queries as only the nodes on the path will be traversed). Take the xor with x of all the nodes in the path till root.
- The maximum xor calculated for the path is the answer.
Below is the implementation of the above approach:Â Â
C++14
// CPP implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Tree nodeclass Node{public:Â Â Â Â int data;Â Â Â Â Node *left, *right;Â
    Node(int data)    {        this->data = data;        this->left = NULL;        this->right = NULL;    }};Â
// Recursive function to update// the parent array such that parent[i]// stores the parent of ivoid updateParent(int *parent, Node *node){    // If node is null then return    if (node == NULL)        return;Â
    // If left child of the node is not    // null then set node as the parent    // of its left child    if (node->left != NULL)        parent[node->left->data] = node->data;Â
    // If right child of the node is not    // null then set node as the parent    // of its right child    if (node->right != NULL)        parent[node->right->data] = node->data;Â
    // Recursive call for the    // children of current node    updateParent(parent, node->left);    updateParent(parent, node->right);}Â
// Function to return the maximum value// of a node on the path from root to val// when Xored with xint getMaxXor(Node *root, int n, int val, int x){    // Create the parent array    int *parent = new int[n + 1];    updateParent(parent, root);Â
    // Initialize max with x XOR val    int maximum = x ^ val;Â
    // Get to the parent of val    val = parent[val];Â
    // 0 is the parent of the root    while (val != 0)    {        // Update maximum        maximum = max(maximum, x ^ val);Â
        // Get one level up the tree        val = parent[val];    }    return maximum;}Â
// Driver Codeint main(){Â Â Â Â int n = 6;Â Â Â Â Node *root;Â Â Â Â root = new Node(1);Â Â Â Â root->left = new Node(2);Â Â Â Â root->right = new Node(3);Â Â Â Â root->left->left = new Node(4);Â Â Â Â root->right->right = new Node(5);Â Â Â Â root->right->right->left = new Node(6);Â
    int val = 6, x = 4;    cout << getMaxXor(root, n, val, x) << endl;Â
    return 0;}Â
// This code is contributed by// sanjeev2552 |
Java
// Java implementation of the approachpublic class GFG {Â
    // Tree node    static class Node {        int data;        Node left, right;        Node(int data)        {            this.data = data;            left = null;            right = null;        }    }Â
    // Recursive function to update    // the parent array such that parent[i]    // stores the parent of i    static void updateParent(int parent[],                             Node node)    {Â
        // If node is null then return        if (node == null)            return;Â
        // If left child of the node is not        // null then set node as the parent        // of its left child        if (node.left != null)            parent[node.left.data] = node.data;Â
        // If right child of the node is not        // null then set node as the parent        // of its right child        if (node.right != null)            parent[node.right.data] = node.data;Â
        // Recursive call for the        // children of current node        updateParent(parent, node.left);        updateParent(parent, node.right);    }Â
    // Function to return the maximum value    // of a node on the path from root to val    // when Xored with x    static int getMaxXor(Node root,                         int n, int val, int x)    {Â
        // Create the parent array        int parent[] = new int[n + 1];        updateParent(parent, root);Â
        // Initialize max with x XOR val        int max = x ^ val;Â
        // Get to the parent of val        val = parent[val];Â
        // 0 is the parent of the root        while (val != 0) {Â
            // Update maximum            max = Math.max(max, x ^ val);Â
            // Get one level up the tree            val = parent[val];        }        return max;    }Â
    // Driver code    public static void main(String[] args)    {        int n = 6;        Node root = new Node(1);        root.left = new Node(2);        root.right = new Node(3);        root.left.left = new Node(4);        root.right.right = new Node(5);        root.right.right.left = new Node(6);Â
        int val = 6, x = 4;        System.out.println(getMaxXor(root, n, val, x));    }} |
Python3
# Python3 implementation of the approachÂ
# Tree nodeclass Node:    def __init__(self, data):        self.data = data        self.left = None        self.right = None     # Recursive function to update# the parent array such that parent[i]# stores the parent of idef updateParent(parent, node):Â
    # If node is None then return    if (node == None):        return parentÂ
    # If left child of the node is not    # None then set node as the parent    # of its left child    if (node.left != None):        parent[node.left.data] = node.dataÂ
    # If right child of the node is not    # None then set node as the parent    # of its right child    if (node.right != None):        parent[node.right.data] = node.dataÂ
    # Recursive call for the    # children of current node    parent = updateParent(parent, node.left)    parent = updateParent(parent, node.right)    return parentÂ
# Function to return the maximum value# of a node on the path from root to val# when Xored with xdef getMaxXor(root, n, val, x):Â
    # Create the parent array    parent = [0]*(n + 1)    parent=updateParent(parent, root)Â
    # Initialize max with x XOR val    maximum = x ^ valÂ
    # Get to the parent of val    val = parent[val]Â
    # 0 is the parent of the root    while (val != 0):             # Update maximum        maximum = max(maximum, x ^ val)Â
        # Get one level up the tree        val = parent[val]         return maximumÂ
# Driver Coden = 6Â
root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.right.right = Node(5)root.right.right.left = Node(6)Â
val = 6x = 4print( getMaxXor(root, n, val, x) )Â
# This code is contributed by Arnab Kundu |
C#
// C# implementation of the approach using System;Â
class GFG{Â
    // Tree node    public class Node     {        public int data;        public Node left, right;        public Node(int data)        {            this.data = data;            left = null;            right = null;        }    }Â
    // Recursive function to update    // the parent array such that parent[i]    // stores the parent of i    static void updateParent(int []parent,                             Node node)    {Â
        // If node is null then return        if (node == null)            return;Â
        // If left child of the node is not        // null then set node as the parent        // of its left child        if (node.left != null)            parent[node.left.data] = node.data;Â
        // If right child of the node is not        // null then set node as the parent        // of its right child        if (node.right != null)            parent[node.right.data] = node.data;Â
        // Recursive call for the        // children of current node        updateParent(parent, node.left);        updateParent(parent, node.right);    }Â
    // Function to return the maximum value    // of a node on the path from root to val    // when Xored with x    static int getMaxXor(Node root, int n,                          int val, int x)    {Â
        // Create the parent array        int []parent = new int[n + 1];        updateParent(parent, root);Â
        // Initialize max with x XOR val        int max = x ^ val;Â
        // Get to the parent of val        val = parent[val];Â
        // 0 is the parent of the root        while (val != 0)         {Â
            // Update maximum            max = Math.Max(max, x ^ val);Â
            // Get one level up the tree            val = parent[val];        }        return max;    }Â
    // Driver code    public static void Main(String[] args)    {        int n = 6;        Node root = new Node(1);        root.left = new Node(2);        root.right = new Node(3);        root.left.left = new Node(4);        root.right.right = new Node(5);        root.right.right.left = new Node(6);Â
        int val = 6, x = 4;        Console.WriteLine(getMaxXor(root, n, val, x));    }}Â
// This code is contributed by Princi Singh |
Javascript
<script>Â
// Javascript implementation of above approachÂ
// Tree nodeclass Node{Â Â Â Â constructor(data)Â Â Â Â {Â Â Â Â Â Â Â Â this.left = null;Â Â Â Â Â Â Â Â this.right = null;Â Â Â Â Â Â Â Â this.data = data;Â Â Â Â }}Â
// Recursive function to update// the parent array such that parent[i]// stores the parent of ifunction updateParent(parent, node){         // If node is null then return    if (node == null)        return;Â
    // If left child of the node is not    // null then set node as the parent    // of its left child    if (node.left != null)        parent[node.left.data] = node.data;Â
    // If right child of the node is not    // null then set node as the parent    // of its right child    if (node.right != null)        parent[node.right.data] = node.data;Â
    // Recursive call for the    // children of current node    updateParent(parent, node.left);    updateParent(parent, node.right);}Â
// Function to return the maximum value// of a node on the path from root to val// when Xored with xfunction getMaxXor(root, n, val, x){         // Create the parent array    let parent = new Array(n + 1);    parent.fill(0);    updateParent(parent, root);Â
    // Initialize max with x XOR val    let max = x ^ val;Â
    // Get to the parent of val    val = parent[val];Â
    // 0 is the parent of the root    while (val != 0)    {                 // Update maximum        max = Math.max(max, x ^ val);Â
        // Get one level up the tree        val = parent[val];    }    return max;}Â
// Driver codelet n = 6;let root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.right.right = new Node(5);root.right.right.left = new Node(6);Â
let val = 6, x = 4;document.write(getMaxXor(root, n, val, x));Â
// This code is contributed by divyeshrabadiya07Â
</script> |
Output:Â
7
Â
Time Complexity: O(N)
Â
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



