https://leetcode.com/problems/binary-tree-right-side-view/description/
Question:
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.
JavaScript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var rightSideView = function(root) {
};
Example 1
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Example 2
Input: root = [1,null,3]
Output: [1,3]
Example 3
Input: root = []
Output: []
Concept:
- Tree
- BFS (Breadth First Search)
- Use for loop to go through each level, and get the 1st node in a level
- Get the nodes per level by queue.length
- Move
right to left
, by push node.right first, and node.right
Javascript solution:
var rightSideView = function (root) {
const result = []
// BFS
const queue = [root]
while (queue.length > 0) {
const levelLength = queue.length
for (let i = 0; i < levelLength; i++) {
const node = queue.shift()
if (node) {
if (i === 0) result.push(node.val)
if (node.right) queue.push(node.right) // right first
if (node.left) queue.push(node.left)
}
}
}
return result
}
Solution steps:
- Create array “result”, for our return
- Create array “queue”, for BFS, default with root in it
- Start a while loop for BFS, condition for queue is not empty
- [while loop] Create variable “levelLength”, which is the amount of nodes in current level
- [while loop] Start a for loop, for each nodes in this level
- [while loop] [for loop] get the left “node” right queue with .shift()
- [while loop] [for loop] if “node” is not empty, push the
first
node.val in the level to the result, by checking 1 === 0. Then push node.right, and node.left to queue (if not null), making sure to push right first, then left. - return result
Reference:
(BFS, left to right solution)