Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.59 KB | None | 0 0
  1. class Tree {
  2. constructor(value, children = []) {
  3. this.value = value
  4. this.children = children
  5. }
  6.  
  7. isLeaf() {
  8. return this.children.length === 0
  9. }
  10.  
  11. // traverses the tree depth first, and applies fn on each node
  12. traverse(fn) {
  13. fn(this)
  14. if (!this.isLeaf()) {
  15. this.children.forEach(n => n.traverse(fn))
  16. }
  17. }
  18.  
  19. // prints out the tree depth-first
  20. print() { this.traverse(n => console.log(n.value)) }
  21.  
  22. }
  23.  
  24. const t = new Tree(42, [
  25. new Tree(12, [
  26. new Tree(5, []),
  27. new Tree(14, [])
  28. ]),
  29. new Tree(32, [
  30. new Tree(30, []),
  31. new Tree(36, [])
  32. ])
  33. ])
  34.  
  35. t.print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement