Skip to content

Commit

Permalink
solve: binary tree level order traversal
Browse files Browse the repository at this point in the history
  • Loading branch information
wogha95 committed Nov 15, 2024
1 parent a43dd47 commit ecc65dd
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions binary-tree-level-order-traversal/wogha95.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,59 @@
/**
* 2차
* 각 level의 node 수만큼 끊어서 순회하기
*
* TC: O(N)
* SC: O(N)
* N: total of nodes
*/

/**
* 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) {
return [];
}

const result = [];
const queue = [root];

while (queue.length > 0) {
const level = queue.length;
const currentLevelValList = [];

for (let i = 0; i < level; i++) {
const current = queue.shift();

currentLevelValList.push(current.val);

if (current.left) {
queue.push(current.left);
}

if (current.right) {
queue.push(current.right);
}
}

result.push(currentLevelValList);
}

return result;
};

/**
* 1차
* level과 노드를 queue에 추가해서 정답만들기
*
* TC: O(N)
* SC: O(N)
Expand Down

0 comments on commit ecc65dd

Please sign in to comment.