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

LeetCode 102 - Binary Tree Level Order Traversal (Medium)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 102๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ด์ง„ ํŠธ๋ฆฌ์˜ level order ํƒ์ƒ‰์„ ๊ตฌํ˜„ํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
๋Œ€ํ‘œ์ ์ธ BFS ๋ฌธ์ œ๋กœ ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•ด์ฃผ๋ฉฐ ํƒ์ƒ‰์„ ์ˆ˜ํ–‰ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ด๋•Œ ์ฃผ์˜ํ• ์ ์€ ๋ฌธ์ œ ์ถœ๋ ฅ ํ˜•์‹์ด level ์— ์žˆ๋Š” ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ํ•˜๋‚˜๋กœ ๋ฌถ์–ด์„œ ๋ฐฐ์—ด๋กœ ์ถ”๊ฐ€ํ•ด์•ผํ•˜๋ฏ€๋กœ
๊ฐ๊ฐ์˜ BFS ๋‹จ๊ณ„๋งˆ๋‹ค ํ˜„์žฌ ํ์— ์กด์žฌํ•˜๋Š” ๋ชจ๋“  ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜ ๋งŒํผ ๋ฃจํ”„๋ฅผ ๋Œ๋ฉฐ ์ž์‹ ๋…ธ๋“œ๋“ค์„ ํƒ์ƒ‰ํ•ด์•ผํ•œ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

๋งˆ์น˜ ๋ฐฑ์ค€์˜ ํ† ๋งˆํ†  ๋ฌธ์ œ์™€ ๋น„์Šทํ•œ ๋ฐฉ์‹์ด์ฃ . ์ด๋ ‡๊ฒŒ ํ•ด์•ผ ํ˜„์žฌ ๋ ˆ๋ฒจ์— ์กด์žฌํ•˜๋Š” ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ํ•จ๊ป˜ ๋ฐฐ์—ด๋กœ ๋ฌถ์–ด์ค„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * 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 levelOrder = function (root) {
  if (!root) return [];

  const answer = [];

  function bfs(root) {
    const Q = [];
    Q.push(root);

    while (Q.length) {
      const loop = Q.length;
      const visit = [];

      for (let i = 0; i < loop; i++) {
        const here = Q.shift();
        visit.push(here.val);

        if (here.left) Q.push(here.left);
        if (here.right) Q.push(here.right);
      }

      if (visit.length) answer.push(visit);
    }
  }

  bfs(root);
  return answer;
};
๋ฐ˜์‘ํ˜•

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

LeetCode 136 - Single Number (Easy)  (0) 2021.03.03
LeetCode 104 - Maximum Depth of Binary Tree (Easy)  (0) 2021.03.03
LeetCode 617 - Merge Two Binary Trees (Easy)  (0) 2021.03.03
LeetCode 98 - Validate Binary Search Tree (Medium)  (0) 2021.03.03
LeetCode 130 - Surrounded Regions (Medium)  (0) 2021.03.03

๐Ÿ’ฌ ๋Œ“๊ธ€