Created
January 9, 2023 12:39
-
-
Save Babatunde13/f4ccd02f18835ac893c4e66f42fc0e03 to your computer and use it in GitHub Desktop.
A simple TypeScript functions to show how the trees data structues are implemented
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function walkPreTree(curr: BinaryNode<number> | undefined, path: number[]): number[] { | |
if (!curr) return path | |
path.push(curr.value) | |
walkPreTree(curr.left, path) | |
walkPreTree(curr.right, path) | |
return path | |
} | |
function walkInTree(curr: BinaryNode<number> | undefined, path: number[]): number[] { | |
if (!curr) return path | |
walkInTree(curr.left, path) | |
path.push(curr.value) | |
walkInTree(curr.right, path) | |
return path | |
} | |
function walkPostTree(curr: BinaryNode<number> | undefined, path: number[]): number[] { | |
if (!curr) return path | |
walkInTree(curr.left, path) | |
walkInTree(curr.right, path) | |
path.push(curr.value) | |
return path | |
} | |
export function preOrderSearch(head: BinaryNode<number>): number[] { | |
return walkPreTree(head, []) | |
} | |
type BinaryNode<T> = { | |
value: T | |
left: BinaryNode<T> | null | |
right: BinaryNode<T> | null | |
} | |
export function inOrderSearch(head: BinaryNode<number>): number[] { | |
return walkInTree(head, []) | |
} | |
export function postOrderSearch(head: BinaryNode<number>): number[] { | |
return walkPostTree(head, []) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment