Created
August 20, 2022 05:37
-
-
Save hawaijar/f1bf9911f2f420eddc9d28b320509ce6 to your computer and use it in GitHub Desktop.
Binary Tree Traversals
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
| 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