|
| 1 | +// Source : https://leetcode.com/problems/binary-tree-right-side-view |
| 2 | +// Author : Dean Shi |
| 3 | +// Date : 2021-11-09 |
| 4 | + |
| 5 | +/*************************************************************************************** |
| 6 | + * Given the root of a binary tree, imagine yourself standing on the right side of it, |
| 7 | + * return the values of the nodes you can see ordered from top to bottom. |
| 8 | + * |
| 9 | + * Example 1: |
| 10 | + * |
| 11 | + * Input: root = [1,2,3,null,5,null,4] |
| 12 | + * Output: [1,3,4] |
| 13 | + * |
| 14 | + * Example 2: |
| 15 | + * |
| 16 | + * Input: root = [1,null,3] |
| 17 | + * Output: [1,3] |
| 18 | + * |
| 19 | + * Example 3: |
| 20 | + * |
| 21 | + * Input: root = [] |
| 22 | + * Output: [] |
| 23 | + * |
| 24 | + * Constraints: |
| 25 | + * |
| 26 | + * The number of nodes in the tree is in the range [0, 100]. |
| 27 | + * -100 <= Node.val <= 100 |
| 28 | + * |
| 29 | + * |
| 30 | + ***************************************************************************************/ |
| 31 | + |
| 32 | +/** |
| 33 | + * Definition for a binary tree node. |
| 34 | + * function TreeNode(val, left, right) { |
| 35 | + * this.val = (val===undefined ? 0 : val) |
| 36 | + * this.left = (left===undefined ? null : left) |
| 37 | + * this.right = (right===undefined ? null : right) |
| 38 | + * } |
| 39 | + */ |
| 40 | +/** |
| 41 | + * @param {TreeNode} root |
| 42 | + * @return {number[]} |
| 43 | + */ |
| 44 | +var rightSideView = function(root) { |
| 45 | + if (!root) return [] |
| 46 | + |
| 47 | + const result = [root.val] |
| 48 | + |
| 49 | + let currLevel = [root] |
| 50 | + while((currLevel = BFSParse(currLevel)).length > 0) { |
| 51 | + result.push(currLevel[currLevel.length - 1].val) |
| 52 | + } |
| 53 | + |
| 54 | + return result |
| 55 | +}; |
| 56 | + |
| 57 | +function BFSParse(queue) { |
| 58 | + const result = [] |
| 59 | + for (let item of queue) {
668D
div> |
| 60 | + if (item.left) { |
| 61 | + result.push(item.left) |
| 62 | + } |
| 63 | + if (item.right) { |
| 64 | + result.push(item.right) |
| 65 | + } |
| 66 | + } |
| 67 | + return result |
| 68 | +} |
0 commit comments