Binary Trees
A binary tree is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It consists of nodes, where each node contains a value and references to its left and right children.
In Ruby, a binary tree can be implemented using a class to represent each node and defining methods to manipulate the tree structure.
Below is the Ruby program to implement a binary tree:
class TreeNode
attr_accessor :value, :left, :right
def initialize(value)
@value = value
@left = nil
@right = nil
end
end
# Create a binary tree
root = TreeNode.new(1)
root.left = TreeNode.new(2)
root.right = TreeNode.new(3)
root.left.left = TreeNode.new(4)
root.left.right = TreeNode.new(5)
# Traverse the binary tree (e.g., inorder traversal)
def inorder_traversal(node)
return if node.nil?
inorder_traversal(node.left)
puts node.value
inorder_traversal(node.right)
end
inorder_traversal(root)
Output:
How to Implement Data Structures in Ruby?
Data structures are fundamental components of any programming language, allowing developers to organize and manipulate data efficiently. In Ruby, a versatile and expressive language, implementing various data structures is straightforward. In this article, we’ll explore how to implement common data structures such as arrays, linked lists, stacks, queues, trees, graphs, and hashmaps in Ruby. The article focuses on discussing data structures in Ruby.
Table of Content
- Singly-Linked Lists
- Doubly-Linked Lists
- Circular Linked Lists
- Queues
- Stack
- Hash Tables
- Sets
- Binary Trees
- AVL Trees (Adelson-Velsky and Landis Trees)
- Graphs
- Persistent Lists
Contact Us