Skip to content

Instantly share code, notes, and snippets.

@hawaijar
Created August 20, 2022 05:37
Show Gist options
  • Save hawaijar/f1bf9911f2f420eddc9d28b320509ce6 to your computer and use it in GitHub Desktop.
Save hawaijar/f1bf9911f2f420eddc9d28b320509ce6 to your computer and use it in GitHub Desktop.
Binary Tree Traversals
export class BinaryTreeNode {
value: number;
left: BinaryTreeNode | null;
right: BinaryTreeNode | null;
constructor(value: number) {
this.value = value;
this.left = null;
this.right = null;
}
}
export function insertLevelOrder(
array: number[],
level: number = 0
): BinaryTreeNode | null {
let root: BinaryTreeNode | null = null;
if (level < array.length) {
root = new BinaryTreeNode(array[level]);
root.left = insertLevelOrder(array, 2 * level + 1);
root.right = insertLevelOrder(array, 2 * level + 2);
}
return root;
}
export function preOrder(
root: BinaryTreeNode | null,
path: number[] = []
): number[] {
if (!root) {
return path;
}
path.push(root.value);
if (root.left) {
preOrder(root.left, path);
}
if (root.right) {
preOrder(root.right, path);
}
return path;
}
export function inOrder(
root: BinaryTreeNode | null,
path: number[] = []
): number[] {
if (!root) {
return path;
}
if (root.left) {
inOrder(root.left, path);
}
path.push(root.value);
if (root.right) {
inOrder(root.right, path);
}
return path;
}
export function postOrder(
root: BinaryTreeNode | null,
path: number[] = []
): number[] {
if (!root) {
return path;
}
if (root.left) {
postOrder(root.left, path);
}
if (root.right) {
postOrder(root.right, path);
}
path.push(root.value);
return path;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment