Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Tree {
- constructor(value, children = []) {
- this.value = value
- this.children = children
- }
- isLeaf() {
- return this.children.length === 0
- }
- // traverses the tree depth first, and applies fn on each node
- traverse(fn) {
- fn(this)
- if (!this.isLeaf()) {
- this.children.forEach(n => n.traverse(fn))
- }
- }
- // prints out the tree depth-first
- print() { this.traverse(n => console.log(n.value)) }
- }
- const t = new Tree(42, [
- new Tree(12, [
- new Tree(5, []),
- new Tree(14, [])
- ]),
- new Tree(32, [
- new Tree(30, []),
- new Tree(36, [])
- ])
- ])
- t.print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement