Skip to content

Instantly share code, notes, and snippets.

@alii
Created September 30, 2021 00:41
Show Gist options
  • Save alii/0084bf5695e35eabbf5b562f4a8f3367 to your computer and use it in GitHub Desktop.
Save alii/0084bf5695e35eabbf5b562f4a8f3367 to your computer and use it in GitHub Desktop.
binary tree implementation so you can win those code interviews 😎
import y from "yaml";
export class TreeNode<T> {
public readonly left?: TreeNode<T>;
public readonly right?: TreeNode<T>;
public readonly value: T;
constructor(
value: T,
left?: TreeNode<T>,
right?: TreeNode<T>
) {
this.value = value;
this.left = left;
this.right = right;
}
toString(): string {
return y.stringify({
left: this.left?.toString() ?? null,
right: this.right?.toString() ?? null,
value: this.value,
});
}
public static invert<T>(
tree: TreeNode<T>
): TreeNode<T> {
const left =
tree.right && TreeNode.invert(tree.right);
const right =
tree.left && TreeNode.invert(tree.left);
return new TreeNode(tree.value, left, right);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment