Created
September 30, 2021 00:41
-
-
Save alii/0084bf5695e35eabbf5b562f4a8f3367 to your computer and use it in GitHub Desktop.
binary tree implementation so you can win those code interviews π
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
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