Skip to content

Commit 56ab713

Browse files
author
hojas
committed
binaryTree levelOrder
1 parent d0d2ff8 commit 56ab713

File tree

2 files changed

+20
-9
lines changed

2 files changed

+20
-9
lines changed

src/1-data-structures/4-tree/binary-tree/BinaryTreeNode.test.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import { describe, expect, it } from 'vitest'
2-
import { BinaryTreeNode, inorderTraversal, postorderTraversal, preorderTraversal } from './BinaryTreeNode'
2+
import {
3+
BinaryTreeNode,
4+
inorderTraversal,
5+
levelOrder,
6+
postorderTraversal,
7+
preorderTraversal,
8+
} from './BinaryTreeNode'
39

410
function createBinaryTree() {
511
const root = new BinaryTreeNode(1)
@@ -20,6 +26,12 @@ describe('binaryTreeNode', () => {
2026
expect(node.right).toBeNull()
2127
})
2228

29+
it('should level order traversal', () => {
30+
const root = createBinaryTree()
31+
const res = levelOrder(root)
32+
expect(res).toEqual([[1], [2, 3], [4, 5, 6, 7]])
33+
})
34+
2335
it('should preorderTraversal', () => {
2436
const root = createBinaryTree()
2537
const res = preorderTraversal(root)

src/1-data-structures/4-tree/binary-tree/BinaryTreeNode.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,21 +22,20 @@ export function levelOrder(root: BinaryTreeNode | null): number[][] {
2222
const res: number[][] = []
2323
const q = [root]
2424

25-
while (q.length) {
25+
while (q.length !== 0) {
2626
const len = q.length
27-
const level = []
27+
const arr: number[] = []
2828

2929
for (let i = 0; i < len; i++) {
3030
const node = q.shift() as BinaryTreeNode
31-
level.push(node.value)
32-
33-
if (node.left) {
31+
arr.push(node.value)
32+
if (node.left)
3433
q.push(node.left)
35-
}
36-
if (node.right) {
34+
if (node.right)
3735
q.push(node.right)
38-
}
3936
}
37+
38+
res.push(arr)
4039
}
4140

4241
return res

0 commit comments

Comments
 (0)