How to use Level Order Traversal In Javascript

Using this approach, we traverse the binary tree in level-order, also known as breadth-first search (BFS). At each level, we keep track of the last node encountered and append it to the result array. This ensures that the right view includes only the rightmost node at each level.

Example: Implementation to show right view of binary tree using level order transversal.

JavaScript
class TreeNode {
    constructor(val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

function rightViewLevelOrder(root) {
    if (!root) return [];

    const result = [];
    const queue = [root];

    while (queue.length > 0) {
        const size = queue.length;
        let lastNode = null;

        for (let i = 0; i < size; i++) {
            const node = queue.shift();
            lastNode = node;

            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }

        result.push(lastNode.val);
    }

    return result;
}

// Example usage
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(4);
root.right.right = new TreeNode(6);

console.log(rightViewLevelOrder(root));

Output
[ 1, 3, 6 ]

Time Complexity: O(n)

Space Complexity: O(n)



JavaScript Program to Print Right View of Binary Tree

The right view of a binary tree refers to the nodes visible when viewed from the right side of the tree. There are multiple approaches to print the right view of a binary tree, each with its own advantages and complexities. In this article, we’ll explore two approaches-

Examples:

Input:
5
/ \
4 6
/ \ / \
5 2 1 3

Output: Right view of the tree is 5 6 3

Input:
5
/
3
/
1

Output: Right view of the tree is 5 3 1

Table of Content

  • Using Recursion
  • Using Level Order Traversal

Similar Reads

Using Recursion

In this approach, we recursively traverse the binary tree while maintaining the current level and the maximum level reached so far. At each level, we only consider the right child if it is the first node encountered at that level. This ensures that the right view includes only the rightmost node at each level....

Using Level Order Traversal

Using this approach, we traverse the binary tree in level-order, also known as breadth-first search (BFS). At each level, we keep track of the last node encountered and append it to the result array. This ensures that the right view includes only the rightmost node at each level....