Created
February 14, 2018 10:13
-
-
Save bor0/faff2f5232a933560dc9ac373730f6b5 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
| // based off of https://github.com/bor0/misc/blob/master/2017/tree.js | |
| // example: https://github.com/bor0/misc/blob/master/2017/tree_test.js | |
| var tree = { | |
| v: 1, | |
| l: { | |
| v: 2, | |
| l: { | |
| v: 3, | |
| l: { v: 4 }, | |
| r: { v: 5 }, | |
| }, | |
| r: { v: 6 }, | |
| }, | |
| r: { | |
| v: 7, | |
| l: { | |
| v: 8, | |
| l: { v: 9 }, | |
| r: { v: 10 }, | |
| }, | |
| r: { v: 11 }, | |
| } | |
| }; | |
| let flat_tree = function(tree) { | |
| let S = [tree], l = []; | |
| while (S.length) { | |
| let v = S.pop(); | |
| l.push(v.v); | |
| if (v.r) S.push(v.r); | |
| if (v.l) S.push(v.l); | |
| } | |
| return l; | |
| }; | |
| console.log(flat_tree(tree)); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More generalized version:
Usage example for callback: