summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authormo <mokha@cisco.com>2017-08-05 10:37:17 -0600
committermo <mokha@cisco.com>2017-08-05 10:37:17 -0600
commita95f896ac09c991bcbd20a7d99418edeaa7296b9 (patch)
treed38b43e7e1eb1b36a78153db903575612804d39b /lib
parent5f3b059538974077f9e2d91f4acbbbb6d180f891 (diff)
add method to print tree.
Diffstat (limited to 'lib')
-rw-r--r--lib/tree.rb42
1 files changed, 25 insertions, 17 deletions
diff --git a/lib/tree.rb b/lib/tree.rb
index e4527d8..a03ff43 100644
--- a/lib/tree.rb
+++ b/lib/tree.rb
@@ -1,22 +1,30 @@
- class Tree
- attr_accessor :value, :left, :right
+class Tree
+ attr_accessor :value, :left, :right
- def initialize(value, left: nil, right: nil)
- @value = value
- @left = left
- @right = right
- end
+ def initialize(value, left: nil, right: nil)
+ @value = value
+ @left = left
+ @right = right
+ end
+
+ def to_a
+ [value, left&.to_a, right&.to_a]
+ end
- def print_tree
- [value, left&.print_tree, right&.print_tree]
- end
+ def print(prefix = '', tail = true)
+ puts(prefix + (tail ? "└── " : "├── ") + value.to_s)
- def to_h
- { value: value, left: left&.to_h, right: right&.to_h }
- end
+ prefix = prefix + (tail ? " " : "│ ")
+ left.print(prefix, false) if left
+ right.print(prefix, false) if right
+ end
+
+ def to_h
+ { value: value, left: left&.to_h, right: right&.to_h }
+ end
- def self.build_from(hash)
- return nil if hash.nil?
- Tree.new(hash[:value], left: build_from(hash[:left]), right: build_from(hash[:right]))
- end
+ def self.build_from(hash)
+ return nil if hash.nil?
+ Tree.new(hash[:value], left: build_from(hash[:left]), right: build_from(hash[:right]))
end
+end