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.
- #invert(root = @root) ⇒ Object
- #sum(root = @root) ⇒ Object
- #to_a(root = @root, arr = [], idx = 0) ⇒ Object
Constructor Details
#initialize(root = nil) ⇒ Tree
Returns a new instance of Tree.
25 26 27 |
# File 'lib/binary_trees.rb', line 25 def initialize(root = nil) @root = root end |
Instance Method Details
#invert(root = @root) ⇒ Object
35 36 37 38 39 40 41 42 |
# File 'lib/binary_trees.rb', line 35 def invert(root = @root) return nil unless root temp = root.left root.left = invert(root.right) root.right = invert(temp) root end |
#sum(root = @root) ⇒ Object
29 30 31 32 33 |
# File 'lib/binary_trees.rb', line 29 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
44 45 46 47 48 49 50 51 |
# File 'lib/binary_trees.rb', line 44 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 |