Given a value K and a binary tree, we have to find out the total number of paths from root to leaf nodes having XOR of all its nodes along the path equal to K.
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) = 6. Subtree 2: 2 / 1 \ 5 This particular path has 3 nodes; 2, 1 and 5 and (2 xor 1 xor 5) = 6.
To solve the question mentioned above we have 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.
XOR of current node’s path = (XOR of the path till the parent) ^ (current node value)
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 path is K, if it is then we increase the count otherwise we do nothing. Finally, print the value in the count.
Below is the implementation of the above approach:
Time Complexity: As in the above approach, we are iterating over each node only once, therefore it will take O(N) time where N is the number of nodes in the Binary tree.
Auxiliary Space: As in the above approach there is no extra space used, therefore the Auxillary Space complexity will be O(1).
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Count of root to leaf paths whose permutation is palindrome in a Binary Tree
- Given a binary tree, print all root-to-leaf paths
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Root to leaf paths having equal lengths in a Binary Tree
- Print all the paths from root, with a specified sum in Binary tree
- Maximum value of Bitwise AND from root to leaf in a Binary tree
- Print the longest path from root to leaf in a Binary tree
- Print the first shortest root to leaf path in a Binary Tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Find the maximum sum leaf to root path in a Binary Tree
- Print root to leaf paths without using recursion
- Sum of all the numbers that are formed from root to leaf paths
- Remove nodes on root to leaf paths of length < K
- Print all root to leaf paths with there relative positions
- Count all k-sum paths in a Binary Tree
- Count even paths in Binary Tree
- Count of Fibonacci paths in a Binary tree
- Count of exponential paths in a Binary Tree
- Count Non-Leaf nodes in a Binary Tree
- Count of paths in given Binary Tree with odd bitwise AND for Q queries
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.