반응형
SMALL
문제
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).
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
코드
/**
* 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 queue = [];
const result = [];
if(root !== null) {
queue.push([root, 0])
}
while(queue.length) {
const [node, level] = queue.shift();
if(!result[level]) result[level] = [];
if(node && node.val !== null)result[level].push(node.val);
if(node && node.left) queue.push([node.left, level + 1])
if(node && node.right) queue.push([node.right, level + 1])
}
return result
};
// 혹은
// If root is null return an empty array
if(!root) return []
const queue = [root] // initialize the queue with root
const levels = [] // declare output array
while(queue.length !== 0){
const queueLength = queue.length // Get the length prior to dequeueing
const currLevel = [] // Declare this level
// loop through to exhaust all options and only to include nodes at currLevel
for(let i = 0; i < queueLength; i++){
// Get next node
const current = queue.shift()
if(current.left){
queue.push(current.left)
}
if(current.right){
queue.push(current.right)
}
// After we add left and right for current, we add to currLevel
currLevel.push(current.val)
}
// Level has been finished. Push into output array
levels.push(currLevel)
}
return levels
}
반응형
LIST
'Coding Interview' 카테고리의 다른 글
알고리즘 유형을 알아보자 (0) | 2022.10.01 |
---|---|
[LeetCode] DP - 42. Trapping Rain Water (0) | 2022.10.01 |
[기타] 코딩테스트에 활용되는 수학 이론 (1) | 2022.09.30 |
[LeetCode] DP - 279. Perfect Squares (feat. 라그랑주의 네제곱수) (0) | 2022.09.30 |
[LeetCode] DFS - 103. Binary Tree Zigzag Level Order Traversal (0) | 2022.09.30 |