Created
May 18, 2020 15:27
-
-
Save blacksheep557/27aafc6776c936bcf1cf9d2ad91a8e81 to your computer and use it in GitHub Desktop.
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 treeToArray(tree) { | |
| let result = [tree['value']]; | |
| let pointer = 0; | |
| while (pointer < result.length) { | |
| if (result[pointer] !== null) { | |
| while (result[result.length - 1] === null) { | |
| result.pop() | |
| } | |
| let children = findNode(tree, result[pointer]); | |
| if(pointer>=result.length){ | |
| break; | |
| } | |
| result.push(...children); | |
| } | |
| pointer++; | |
| } | |
| while (result[result.length - 1] === null) { | |
| result.pop() | |
| } | |
| console.log(result); | |
| return result | |
| } | |
| function findNode(root, target) { | |
| if (root.value === target) { | |
| return [root.left !== undefined ? root.left.value : null, root.right !== undefined ? root.right.value : null] | |
| } else { | |
| if (root.left !== undefined) { | |
| if (findNode(root.left, target) !== undefined) { | |
| return findNode(root.left, target); | |
| } | |
| } | |
| if (root.right !== undefined) { | |
| if (findNode(root.right, target) !== undefined) { | |
| return findNode(root.right, target); | |
| } | |
| } | |
| } | |
| return undefined; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment