Class: TreeLab::BinaryTree

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

Overview

Ruby Reference-based implementation of a Binary Tree

Direct Known Subclasses

BinarySearchTree

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBinaryTree

class constructor



88
89
# File 'lib/treelab.rb', line 88

def initialize()
end

Instance Attribute Details

#rootObject (readonly)

root node



85
86
87
# File 'lib/treelab.rb', line 85

def root
  @root
end

Instance Method Details

#emptyObject

empties the tree



124
125
126
127
128
129
130
# File 'lib/treelab.rb', line 124

def empty
    @root = nil
    if(TreeLab::tree) 
        view_tree(TreeLab::tree)
    end
    return true
end

#heightOfTreeObject

counts the height of the tree



115
116
117
118
119
120
121
# File 'lib/treelab.rb', line 115

def heightOfTree
    if (@root == nil)
        return 0
    else
        return countHeight(@root)
    end
end

#inspectObject



132
133
134
# File 'lib/treelab.rb', line 132

def inspect
    return to_s
end

#isEmpty?Boolean

checks whether the tree is empty

Returns:

  • (Boolean)


102
103
104
# File 'lib/treelab.rb', line 102

def isEmpty?
    return root == nil
end

#noOfNodesObject

counts number of nodes in the tree



107
108
109
110
111
112
# File 'lib/treelab.rb', line 107

def noOfNodes
    if @root == nil
        return 0
    end
    return countNode(@root)
end

#setRoot(node) ⇒ Object



91
92
93
94
95
96
97
98
99
# File 'lib/treelab.rb', line 91

def setRoot(node)
    raise "Value must be a Node!" if node.class != TreeLab::Node
    raise "cannot attach node to itself" if node == self
    @root = node
    if(TreeLab::tree) 
        view_tree(TreeLab::tree)
    end
    return to_s
end

#to_sObject

returns string representation of root node



137
138
139
140
# File 'lib/treelab.rb', line 137

def to_s
    return nil if @root == nil
    return @root.to_s
end