๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 199 - Binary Tree Right Side View (Medium)

by HandHand 2021. 4. 5.

๋ฌธ์ œ

LeetCode - 199๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ด์ง„ ํŠธ๋ฆฌ๋ฅผ ์˜ค๋ฅธ์ชฝ์—์„œ ๋ดค์„ ๋•Œ ๋ณด์ด๋Š” ๋…ธ๋“œ๋“ค์„ ๋†’์ด์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์ด๋ฅผ ์œ„ํ•ด์„œ ๋ฐฉ๋ฌธ ์‹œ ์ด์ „๊นŒ์ง€ ๋ฐฉ๋ฌธํ•œ ํŠธ๋ฆฌ ๋†’์ด ์ถ”์ ์„ ์œ„ํ•ด isVisitedLevel ์ด๋ผ๋Š” ๋ฐฐ์—ด์„ ์œ ์ง€ํ•˜๋ฉฐ

๋ฐฉ๋ฌธ์„ ์˜ค๋ฅธ์ชฝ ์ž์‹ -> ์™ผ์ชฝ ์ž์‹ ์ˆœ์œผ๋กœ ํ•˜๋˜ ์ด์ „์— ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋ ˆ๋ฒจ์ผ ๊ฒฝ์šฐ์—๋งŒ ๋ฐฐ์—ด์— push ํ•ด์ค๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * 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) {
  const answer = [];
  const isVisitedLevel = Array(8).fill(false); // log2 (100) == 6.xxx

  function dfs(root, level) {
    if (!root) {
      return;
    }

    if (!isVisitedLevel[level]) {
      isVisitedLevel[level] = true;
      answer.push(root.val);
    }

    dfs(root.right, level + 1);
    dfs(root.left, level + 1);
  }

  dfs(root, 1);

  return answer;
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 120 - Triangle (Medium)  (0) 2021.04.13
LeetCode 38 - Count and Say (Medium)  (0) 2021.04.13
LeetCode 344 - Reverse String (Easy)  (0) 2021.04.05
LeetCode 1578 - Minimum Deletion Cost to Avoid Repeating Letters (Medium)  (0) 2021.03.08
LeetCode 904 - Fruit Into Baskets (Medium)  (0) 2021.03.08

๐Ÿ’ฌ ๋Œ“๊ธ€