How to use Breadth-first In Javascript

In this approach, we compare two binary trees for level-wise anagram equality. It uses a breadth-first approach, sorting and comparing nodes at each level. If their sorted values match at all levels, it confirms the trees are anagrams, printing “Yes”; otherwise, it prints “No”.

Example: This example shows the use of the above-explained approach.

Javascript




// A Binary Tree Node
class newNode {
    constructor(data) {
        this.data = data;
        this.left = this.right = null;
    }
}
  
function areAnagrams(root1, root2) {
    if (root1 === null && root2 === null) return true;
    if (root1 === null || root2 === null) return false;
  
    let q1 = [root1];
    let q2 = [root2];
  
    while (q1.length > 0 && q2.length > 0) {
        let n1 = q1.length;
        let n2 = q2.length;
  
        if (n1 !== n2) return false;
  
        let currLevel1 = [];
        let currLevel2 = [];
  
        for (let i = 0; i < n1; i++) {
            let node1 = q1.shift();
            let node2 = q2.shift();
  
            currLevel1.push(node1.data);
            currLevel2.push(node2.data);
  
            if (node1.left) q1.push(node1.left);
            if (node1.right) q1.push(node1.right);
            if (node2.left) q2.push(node2.left);
            if (node2.right) q2.push(node2.right);
        }
  
        currLevel1.sort();
        currLevel2.sort();
  
        if (currLevel1.join() !== currLevel2.join()) {
            return false;
        }
    }
  
    return true;
}
  
// Constructing both the trees.
let root1 = new newNode(1);
root1.left = new newNode(3);
root1.right = new newNode(2);
root1.right.left = new newNode(5);
root1.right.right = new newNode(4);
  
let root2 = new newNode(1);
root2.left = new newNode(2);
root2.right = new newNode(3);
root2.left.left = new newNode(4);
root2.left.right = new newNode(5);
  
if (areAnagrams(root1, root2)) {
    console.log("Yes");
} else {
    console.log("No");
}


Output

Yes

Time Complexity: O(N * (M log M))

Space Complexity: O(N + M)

JavaScript to Check if all Levels of Two Trees are Anagrams or Not

In this article, we are going to learn about Checking if all levels of two trees are anagrams or not. Checking if all levels of two trees are anagrams means verifying that for each level in two binary trees, the nodes at that level have the same characters with the same frequencies, indicating that they can be rearranged to form the same string.

Table of Content

  • Using breadth-first
  • Using Naive Approach

Similar Reads

Using Breadth-first

...

Using Naive Approach

In this approach, we compare two binary trees for level-wise anagram equality. It uses a breadth-first approach, sorting and comparing nodes at each level. If their sorted values match at all levels, it confirms the trees are anagrams, printing “Yes”; otherwise, it prints “No”....

Contact Us