Skip to content

Commit

Permalink
2. Binary Tree Level Order Traversal
Browse files Browse the repository at this point in the history
  • Loading branch information
Sunjae95 committed Nov 13, 2024
1 parent d74dfc1 commit def6a43
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions binary-tree-level-order-traversal/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @description
* 동일한 depth를 방문해야하므로 bfs 및 트리 순회
*
* n = length of node of root
* time complexity: O(n)
* space complexity: O(n)
*/
var levelOrder = function (root) {
if (!root) return [];

const answer = [];
const queue = [root];
let queueCurrentIndex = 0;

while (queue.length > queueCurrentIndex) {
answer.push([]);
const answerLastIndex = answer.length - 1;
const depthEndIndex = queue.length;

while (depthEndIndex !== queueCurrentIndex) {
const tree = queue[queueCurrentIndex++];

answer[answerLastIndex].push(tree.val);
if (tree.left) queue.push(tree.left);
if (tree.right) queue.push(tree.right);
}
}

return answer;
};

0 comments on commit def6a43

Please sign in to comment.