Class: Tree
- Inherits:
-
Object
- Object
- Tree
- Defined in:
- lib/binary_trees.rb
Instance Method Summary collapse
-
#initialize(root = nil) ⇒ Tree
constructor
A new instance of Tree.
- #sum(root = @root) ⇒ Object
- #to_a(root = @root, arr = [], idx = 0) ⇒ Object
Constructor Details
#initialize(root = nil) ⇒ Tree
Returns a new instance of Tree.
24 25 26 |
# File 'lib/binary_trees.rb', line 24 def initialize(root = nil) @root = root end |
Instance Method Details
#sum(root = @root) ⇒ Object
28 29 30 31 32 |
# File 'lib/binary_trees.rb', line 28 def sum(root = @root) return 0 if root.nil? root.val + sum(root.left) + sum(root.right) end |
#to_a(root = @root, arr = [], idx = 0) ⇒ Object
34 35 36 37 38 39 40 41 |
# File 'lib/binary_trees.rb', line 34 def to_a(root = @root, arr = [], idx = 0) return [] if root.nil? arr[idx] = root.val to_a(root.left, arr, idx * 2 + 1) if root.left to_a(root.right, arr, idx * 2 + 2) if root.right arr end |