Leetcode - Binary Tree Level Order Traversal

·2022년 1월 14일
0

Algorithm

목록 보기
9/19
post-thumbnail

Problem

Binary Tree Level Order Traversal

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

이진트리 root가 주어 졌을 때, 계층의 순서대로 순회하는 값을 구하시오.
(좌측부터 우측으로, 계층별로)

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example 2:

Input: root = [1]
Output: [[1]]

Example 3:

Input: root = []
Output: []

Constraints:

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

Solution

JavaScript

/**
 * 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) {
    const result = []
    if(root === null) return result
    const queue = []
    queue.push(root)
    while(queue.length > 0) {
        let levelSize = queue.length
        const currentLevel = []
        for(let i = 0; i < levelSize; i++) {
           let currentNode = queue.shift()
           currentLevel.push(currentNode.val)
            if(currentNode.left !== null) queue.push(currentNode.left)
            if(currentNode.right !== null) queue.push(currentNode.right)
        }
        result.push(currentLevel)
    }
    return result

Feedback은 언제나 환영입니다🤗

profile
You only get one life. It's actually your duty to live it as fully as possible.

0개의 댓글