Check if the given Permutation is a Valid BFS of a Given Tree


In this problem, we will check whether we can get the permutation of 1 to N elements given array using the BFS (Breadth−first search) traversal with the given binary tree.

Here, we will traverse the tree and find all possible permutations using the BFS traversal. After that, we can check whether any BFS traversal result matches the array permutation.

Problem statement − We have given an array of size containing the first N positive integers in random order. Also, we have given a tree containing the first N numbers as a tree node. We need to check whether we can get array elements in the same order in the BFS traversal of the tree.

Sample examples

Input

permutation = {1, 3, 2, 6, 4, 5, 8, 7};
             1
           /   \
          2     3
        /  \    / 
       4    5   6    
      /  \ 
      7   8  

Output

Yes

Explanation − Using the BFS traversal, we can traverse the binary tree's right or left child node. In the second level, we can traverse the right node first and second node after that. Also, in the last level, we traverse the right node first and the left node after that.

Input

permutation = {1, 5, 2, 6, 4, 3, 8, 7};
             1
           /   \
          2     3
        /  \    / 
       4    5   6    
      /  \ 
     7   8  

Output

No

Explanation − The second level of the binary tree doesn’t contain 5. So, it is not possible to get the given permutation using the BFS traversal.

Input

permutation = {1, 4, 3, 2}
            1
           /   
          4
         / \
        2   3

Output

Yes

Explanation − All BFS permutation of the given binary tree is given below, and the given array is one of them.

  • [1, 4, 2, 3]

  • [1, 4, 3, 2]

Approach

In this approach, we will use the two−dimension array to create a binary tree. Also, we will use the unordered set and queue data structure to solve the problem.

Here, the main logic for solving the problem is that store all nodes of each level in the set and create a queue of such sets. So, we can take nodes from the set and traverse their child nodes. For each node, we can traverse either the right node first or the left node first.

Algorithm

Step 1 − Create a vector list of size N + 1. Also, insert elements to create a binary tree.

Step 2 − If bin_tree[permutation[0]].size() is 0, return false, as the first element of the permutation is not present in the array.

Step 3 − Define the unordered set named ‘vis’ to store the visited elements and ‘level_nodes’ to store the elements of the current nodes. Also, define the queue to store the unordered sets of each level.

Step 4 − Insert the first element of the array into the level_nodes set, and insert the set into the queue.

Step 5 − Make iterations using the while loop until the queue is not empty and the array index is less than the array length.

Step 6 − If the current array element exists in the ‘vis’ set, return false, as the element is already visited.

Step 7 − Insert the current array element into the ‘vis’ node.

Step 8 − If the first set into the queue is empty, remove it.

Step 9 − Take the first set into the level_nodes from the queue.

Step 10 − If the level_nodes doesn’t contain the current array element, return false.

Step 11 − Clear the level_nodes set using the clear() method.

Step 12 − Traverse all connected nodes to the current element in the binary tree.

Step 12.1 − If the current node is not visited, insert it into the level_nodes set.

Step 13 − If level_nodes is not empty, insert it into the queue.

Step 14 − Remove the current array element from the first set of the queue.

Step 15 − Return true after completing all iteration of the while loop.

Example

#include <bits/stdc++.h>
using namespace std;

bool checkForValidPerm(vector<int> &permutation, vector<int> *bin_tree) {
    // When the first element is not present in the tree
    if (bin_tree[permutation[0]].size() == 0) {
        return false;
    }
    // Total nodes in permutation
    int len = permutation.size();
    unordered_set<int> vis;
    // To store nodes of the current level
    unordered_set<int> level_nodes;
    level_nodes.insert(permutation[0]);
    // For BFS traversal
    queue<unordered_set<int>> que;
    que.push(level_nodes);
    int p = 0;
    while (!que.empty() && p < len) {
        // If the node is already visited
        if (vis.count(permutation[p])) {
            return false;
        }
        vis.insert(permutation[p]);
        // When all nodes of the first node are visited
        if (que.front().empty()) {
            que.pop();
        }
        // When an element is not found
        level_nodes = que.front();
        if (level_nodes.count(permutation[p]) == 0) {
            return false;
        }
        level_nodes.clear();
        // Push all child node to level_nodes
        for (int &q : bin_tree[permutation[p]]) {
            if (!vis.count(q)) {
                level_nodes.insert(q);
            }
        }
        if (!level_nodes.empty()) {
            // Insert level_nodes to queue
            que.push(level_nodes);
        }
        // Remove the current node
        que.front().erase(permutation[p]);
        p++;
    }
    return true;
}
int main() {
    int n = 8;
    // Given tree
    vector<int> bin_tree[n + 1];
    bin_tree[1].push_back(2);
    bin_tree[1].push_back(3);
    bin_tree[2].push_back(4);
    bin_tree[2].push_back(5);
    bin_tree[3].push_back(6);
    bin_tree[4].push_back(7);
    bin_tree[4].push_back(8);
    vector<int> permutation = {1, 3, 2, 6, 4, 5, 8, 7};
    if (checkForValidPerm(permutation, bin_tree)) {
        cout << "Yes, the given permutation is valid BFS traversal." << endl;
    } else {
        cout << "No, the given permutation is not a valid BFS traversal." << endl;
    }
    return 0;
}

Output

Yes, the given permutation is valid BFS traversal.

Time complexity − O(N*logN), where N is the number of array elements.

Space complexity − O(N) to store tree elements in set and queue.

In this problem, we have used the level order traversal with the BFS traversal. While traversing each level, we choose to either visit the left or right child node. Programmers may use the recursive function to find all permutations of BFS traversal.

Updated on: 02-Aug-2023

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements