From 488ea7960b628b85fbb8d0e8b7c20c090f5033fa Mon Sep 17 00:00:00 2001 From: ergz Date: Mon, 4 Sep 2023 23:49:08 -0700 Subject: [PATCH] adds ts for tree searches --- ts/bfs.test.ts | 38 +++++++++++++++++++++++++++++++ ts/tree.ts | 47 +++++++++++++++++++++++++++++++++++++++ ts/tree_traversal.test.ts | 44 ++++++++++++++++++++++++++++++++++++ 3 files changed, 129 insertions(+) create mode 100644 ts/bfs.test.ts create mode 100644 ts/tree.ts create mode 100644 ts/tree_traversal.test.ts diff --git a/ts/bfs.test.ts b/ts/bfs.test.ts new file mode 100644 index 0000000..a65838e --- /dev/null +++ b/ts/bfs.test.ts @@ -0,0 +1,38 @@ +import { tree } from "./tree" + +type BinaryNode = { + value: T; + left: BinaryNode | null; + right: BinaryNode | null; +}; + + +function bfs(head: BinaryNode | null, needle: number): boolean { + const q: (BinaryNode | null)[] = [head]; + + while (q.length) { + const current = q.shift() as BinaryNode; + + if (current.value === needle) { + return true; + } + + if (current.left) { + q.push(current.left); + } + + if (current.right) { + q.push(current.right); + } + } + + return false; +} + + +test("bfs search works a number of values", function () { + expect(bfs(tree, 20)).toEqual(true); + expect(bfs(tree, -20)).toEqual(false); + expect(bfs(tree, 10)).toEqual(true); + expect(bfs(tree, 7)).toEqual(true); +}) \ No newline at end of file diff --git a/ts/tree.ts b/ts/tree.ts new file mode 100644 index 0000000..6900103 --- /dev/null +++ b/ts/tree.ts @@ -0,0 +1,47 @@ +type BinaryNode = { + value: T; + left: BinaryNode | null; + right: BinaryNode | null; +}; + +export const tree: BinaryNode = { + value: 20, + right: { + value: 50, + right: { + value: 100, + right: null, + left: null, + }, + left: { + value: 30, + right: { + value: 45, + right: null, + left: null, + }, + left: { + value: 29, + right: null, + left: null, + } + }, + }, + left: { + value: 10, + right: { + value: 15, + right: null, + left: null, + }, + left: { + value: 5, + right: { + value: 7, + right: null, + left: null, + }, + left: null, + } + } +}; \ No newline at end of file diff --git a/ts/tree_traversal.test.ts b/ts/tree_traversal.test.ts new file mode 100644 index 0000000..d5e2a8b --- /dev/null +++ b/ts/tree_traversal.test.ts @@ -0,0 +1,44 @@ +import { tree } from "./tree" + +type BinaryNode = { + value: T; + left: BinaryNode | null; + right: BinaryNode | null; +}; + +// pre order +function walk(current: BinaryNode | null, path: number[]): number[] { + if (!current) { + return path; + } + + path.push(current.value); + walk(current.left, path); + walk(current.right, path); + + return path; + +} + +function pre_order_search(head: BinaryNode): number[] { + const path: number[] = []; + walk(head, path); + + return path; + +} + +test("Pre order", function () { + expect(pre_order_search(tree)).toEqual([ + 20, + 10, + 5, + 7, + 15, + 50, + 30, + 29, + 45, + 100, + ]); +}); \ No newline at end of file