LeetCode-199. Binary Tree Right Side View

问题描述

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.

Example :

img

1
2
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
* @Description: 199. Binary Tree Right Side View
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* 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[]}
*/
const rightSideView = function (root) {
if (!root) {
return []
}
const queue = [root]
const res = []

while (queue.length) {
let curLength = queue.length
let cur = null
while (curLength--) {
cur = queue.shift()
if (cur.left) {
queue.push(cur.left)
}
if (cur.right) {
queue.push(cur.right)
}
}
res.push(cur.val)
}
return res
}