DEV Community

codingpineapple
codingpineapple

Posted on

1 1

199. Binary Tree Right Side View

Description:

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

var rightSideView = function(root) {
    const output = [];
    // Return an emtpy array if the root is null
    if(!root) return output
    const queue = [];
    queue.push(root)
    while(queue.length) {
        // Push the first item in the queue to the output array
        // We populate the queue from right most node to left most node
        // Nodes in the front of the queue will be the closest to the right side
        output.push(queue[0].val);
        const levelLength = queue.length;
        // Add nodes into the queue from right to left
        for(let i = 0; i < levelLength; i++) {
            const cur = queue.shift();
            if(cur.right) queue.push(cur.right)
            if(cur.left) queue.push(cur.left)
        }
    }
    return output;
};
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay