< 문제 간단설명 >
Level Order, 즉 한 Level(=depth)씩 탐색하는 문제이다. 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 === null) return [];
let result = [];
let queue = [];
queue.push(root);
while(queue.length) {
let level = [];
let len = queue.length;
for(let i=0; i<len; i+=1) {
let node = queue.shift();
level.push(node.val);
node.left ? queue.push(node.left) : null;
node.right ? queue.push(node.right) : null;
}
result.push(level);
}
return result;
};
'PS > LeetCode' 카테고리의 다른 글
LeetCode / Binary Search / 278번 / First Bad Version / JS (0) | 2023.04.05 |
---|---|
LeetCode / Binary Search / 704번 / Binary Search / JS (0) | 2023.04.05 |
LeetCode / Tree / 589번 / N-ary Tree Preorder Traversal / JS (0) | 2023.04.05 |
LeetCode / Greedy / 409번 / Longest Palindrome / JS (0) | 2023.04.01 |