Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

codingpineapple
codingpineapple

Posted on

     

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)

varrightSideView=function(root){constoutput=[];// Return an emtpy array if the root is nullif(!root)returnoutputconstqueue=[];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 sideoutput.push(queue[0].val);constlevelLength=queue.length;// Add nodes into the queue from right to leftfor(leti=0;i<levelLength;i++){constcur=queue.shift();if(cur.right)queue.push(cur.right)if(cur.left)queue.push(cur.left)}}returnoutput;};
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

More fromcodingpineapple

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp