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;};
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse