Class: Tree

Inherits:
Object
  • Object
show all
Defined in:
lib/binary_trees.rb

Instance Method Summary collapse

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_array(root = @root, arr = [], idx = 0) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/binary_trees.rb', line 34

def to_array(root = @root, arr = [], idx = 0)
  return [] if root.nil?

  arr[idx] = root.val
  to_array(root.left, arr, idx * 2 + 1) if root.left
  to_array(root.right, arr, idx * 2 + 2) if root.right
  arr
end