Check if given Trees can be made mirror images of each other in K swaps
Given two binary tree with same structure but may have different arrangement of value and given an integer K. The task is to check that after exactly K swap on first tree, will it become mirror of second one. In one swap we take two node of same parent and swap its left and right subtree.
Input: K = 1
/ \ / \
2 3 2 3
Input: K = 4
/ \ / \
25 15 25 15
/ \ / \ / \ / \
7 9 10 21 10 21 9 7
Explanation: Here first we need to swap two pairs (25, 15) and (10 ,21) in the first tree hence K = 2. And then we do swap of (21, 7) and (10, 9) therefore here is total of 4 swap.
Approach: The basic approach to solve this problem is to use recursion and stack based on below idea:
Follow the steps below to implement the above approach:
- Check all the respective nodes of both the trees one by one with the help of iterative inorder traversal.
- If found that the respective data parts of both the trees are not matching, then we simply increment the count of swaps needed
- Once the traversal is complete, check for below condition and return Yes if any of below condition is true:
- if our count is same as K, or
- if count is less than K and (K – count) is even,
- Else return No.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)