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가 주어 졌을 때, 계층의 순서대로 순회하는 값을 구하시오.
(좌측부터 우측으로, 계층별로)
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Input: root = [1]
Output: [[1]]
Input: root = []
Output: []
[0, 2000].
/**
* 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은 언제나 환영입니다🤗