Advertisement
Guest User

Tree

a guest
Aug 15th, 2016
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.63 KB | None | 0 0
  1. class Tree
  2.     attr_accessor :children, :node_name
  3.    
  4.     def initialize(other={})
  5.         if not other.nil?
  6.             key, children = other.first
  7.             @node_name = key;
  8.             @children = []
  9.             other.values.each {|x| @children << Tree.new(x)}
  10.         end
  11.     end
  12.    
  13.     def visit_all(&block)
  14.         visit &block
  15.         children.each {|c| c.visit_all &block} unless children.nil?
  16.     end
  17.    
  18.     def visit(&block)
  19.         block.call self
  20.     end
  21. end
  22.  
  23.  
  24. t = Tree.new({'grandpa'=>{'dad'=>{'child1'=>{},'child2'=>{}},'uncle'=>{'child3'=>{},'child4'=>{}}}})
  25. t.visit_all {|x| puts x.node_name}
  26. gets
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement