Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add preOrder algorithm for tree data structure. test: add testc… #1323

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Data-Structures/Tree/PreOrder.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
function preOrder (root) {
if (root === null) return []

const left = preOrder(root.left)
const right = preOrder(root.right)

return [root.value, ...left, ...right]
}

export { preOrder }
92 changes: 92 additions & 0 deletions Data-Structures/Tree/test/PreOrder.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { preOrder } from '../PreOrder'

describe('preOrder function', () => {
test('should return an empty array for an empty tree', () => {
const tree = null
expect(preOrder(tree)).toEqual([])
})

test('should return an array with the root value for a tree with only one node', () => {
const tree = {
value: 5,
left: null,
right: null
}
expect(preOrder(tree)).toEqual([5])
})

test('should return the correct array for a tree with multiple nodes', () => {
const tree = {
value: 5,
left: {
value: 3,
left: {
value: 2,
left: null,
right: null
},
right: {
value: 4,
left: null,
right: null
}
},
right: {
value: 7,
left: {
value: 6,
left: null,
right: null
},
right: {
value: 8,
left: null,
right: null
}
}
}
expect(preOrder(tree)).toEqual([5, 3, 2, 4, 7, 6, 8])
})

test('should return the correct array for a tree with a single branch to the left', () => {
const tree = {
value: 5,
left: {
value: 4,
left: {
value: 3,
left: {
value: 2,
left: null,
right: null
},
right: null
},
right: null
},
right: null
}
expect(preOrder(tree)).toEqual([5, 4, 3, 2])
})

test('should return the correct array for a tree with a single branch to the right', () => {
const tree = {
value: 5,
left: null,
right: {
value: 6,
left: null,
right: {
value: 7,
left: null,
right: {
value: 8,
left: null,
right: null
}
}
}
}
expect(preOrder(tree)).toEqual([5, 6, 7, 8])
})
})