VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-if-path-length-is-even-or-odd-between-given-tree-nodes-for-q-queries/

⇱ Find if path length is even or odd between given Tree nodes for Q queries - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find if path length is even or odd between given Tree nodes for Q queries

Last Updated : 23 Jul, 2025

Given a generic tree consisting of N nodes and (N - 1) edges and an array of queries query[] of size Q consisting of the type {A, B}, the task for each query is to check whether the path length between two given nodes A and B is even or odd.

Examples:

Input: query[] = {{2, 4}, {4, 0}}

👁 Image

Output:
Odd
Even
Explanation:
For the 1st query A = 2 and B = 4. The path from A to B is 2 -> 0 -> 1 -> 3 -> 4 having a length of 5 i.e., Odd.
For the 2nd query A = 4 and B = 0. The path from A to B is 4 -> 3 -> 1 -> 0 having a length of 4 i.e., Even.

Approach: The given problem can be efficiently solved by converting the tree into a Bipartite Graph. It can be observed that if the given nodes A and B in a query are on the same side in the constructed bipartite graph, then the path length between A and B must be odd and if A and B are on different sides, then the path length must be odd. Below are the steps to follow:

  • Traverse the given tree using the BFS Traversal.
  • Divide all nodes into 2 sets such that all the two adjacent nodes in the tree are in different sets (i.e., 0 or 1). In order to do so, assign an alternating set number to each level during the BFS traversal by assigning the set number of current nodes = 1 XOR the number of the parent of the current node.
  • After completing the above steps, traverse the given array of queries query[] and if the set number of both the nodes are the same, the path length of A to B is Odd. Otherwise, it is Even.

Below is the implementation of the above approach:


Output: 
Odd
Even

 

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

Comment