199. Binary Tree Right Side View
https://leetcode.com/problems/binary-tree-right-side-view/
js
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var rightSideView = function(root) {
if (!root) {
return []
}
const result = []
let current = [root]
let next = []
while (current.length) {
current.forEach(node => {
if (node.left) {
next.push(node.left)
}
if (node.right) {
next.push(node.right)
}
})
result.push(current[current.length - 1].val)
current = next
next = []
}
return result
};
py
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
result = []
current, nextRow = [root], []
while current:
for node in current:
if node.left:
nextRow.append(node.left)
if node.right:
nextRow.append(node.right)
result.append(current[-1].val)
current = nextRow
nextRow = []
return result