QUESTION:
You are given a tree with N vertices and N-1 edges. Node 1 is the root of the tree.
Each vertex of the given tree is assigned an integer value given in the form of array A. All values are distinct.
You can perform the following operation on the tree:
Swap the nodes that are at the same level in the tree.
You need to perform the above operation such that the values, when viewed from left to right at the same level, are in ascending order.
Determine the minimum number of operations required to make all level values sorted.
Notes
A tree is a connected acyclic graph with no self-loops and multiple edges.
When you swap 2 nodes, the node along with its subtree gets swapped. ( See example for better understanding ).
The edges need to be added to a tree in order of input received. , So, if edges input is (2,10) and (8,2), then if you are traversing children of node 2, you must traverse node 10 first ( if not visited already) as it was present in input first.
Example-1
Given,
N = 4
A= [ 1, 2, 3, 4 ]
edges = [(1,3),(1,2),(3,4)]
Approach
The 2nd level of the tree contains values in order 3, 2.
So, you swap these nodes.
Now, the tree edges are (1, 2), (1, 3), (3, 4)
So, Minimum swaps used = 1.
Note: When you swap the node (2, 3), the parent of 4 will still be 3 as the whole subtree gets swapped.
Example-2:
Given,
N = 5
A=[ 10, 5, 6, 4, 7]
edges= [(1,3), (1, 2), (3, 4),(2,5)]
Approach
Level 1: Contains only one node with value = 10. So, it is in ascending order.
Level 2: Contains 2 nodes with values as 6,5. So, you swap these nodes.
Level 3: Now, level 3 values after the above swap are 7, 4. So, we swap here too.
Total swaps = 2.