Example of how to use Tree Traversal using recursion, and generators
A Pen by Vlad Bezden on CodePen.
'use strict' | |
console.clear() | |
class Node { | |
constructor(val) { | |
this._val = val; | |
this._parent = null; | |
this._children = []; | |
} | |
isRoot() { | |
return isValid(this._parent); | |
} | |
get children() { | |
return this._children; | |
} | |
hasChildren() { | |
return this._children.length > 0; | |
} | |
get value() { | |
return this._val; | |
} | |
set value(val) { | |
this._val = val; | |
} | |
append(child) { | |
child._parent = this; | |
this._children.push(child); | |
return this; | |
} | |
} | |
function* TreeTraversal(node) { | |
yield node.value; | |
if (node.hasChildren()) { | |
for (let child of node.children) { | |
yield *TreeTraversal(child); | |
} | |
} | |
} | |
const church = new Node('Church') | |
const rosser = new Node('Rosser') | |
const turing = new Node('Turing') | |
const kleene = new Node('Kleene') | |
const nelson = new Node('Nelson') | |
const constable = new Node('Constable') | |
const mendelson = new Node('Mendelson') | |
const sacks = new Node('Sacks') | |
const gandy = new Node('Gandy') | |
church.append(rosser).append(turing).append(kleene) | |
kleene.append(nelson).append(constable) | |
rosser.append(mendelson).append(sacks) | |
turing.append(gandy) | |
const root = church | |
// One way to iterate tree | |
// for (let person of TreeTraversal(root)) { | |
// console.log(person); | |
// } | |
const data = [...TreeTraversal(root)] | |
data.map(x => console.log(x)) |
Example of how to use Tree Traversal using recursion, and generators
A Pen by Vlad Bezden on CodePen.