Here is Depth first Tree traversals using ES6 generators, influenced by pep-0255
Currently you must use the --harmony-generators
flag when running node 0.11.x to get access to generators.
Depth first traversals:
Pre-order:
Visit the root.
Traverse the left subtree.
Traverse the right subtree.
In-order:
Traverse the left subtree.
Visit root.
Traverse the right subtree.
Post-order:
Traverse the left subtree.
Traverse the right subtree.
Visit the root.
Show me the code!
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 |
|
Let's create a tree:
1 2 3 4 5 |
|
1 2 3 4 5 6 7 8 |
|
Now if we need to traverse the tree:
1 2 3 4 5 6 7 8 9 |
|
To make it easier, I created a node moudle gntr hope it helps, happy hacking!