Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created August 5, 2016 00:35
Show Gist options
  • Save vlad-bezden/33b558c3960e6846a54458655814e0ad to your computer and use it in GitHub Desktop.
Save vlad-bezden/33b558c3960e6846a54458655814e0ad to your computer and use it in GitHub Desktop.
TreeTraversal
'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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment