File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
snippets/ruby/data-structures Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ ---
2+ title : Binary Tree
3+ description : Implements a basic binary tree with in-order traversal.
4+ author : ACR1209
5+ tags : ruby,data structures,binary tree
6+ ---
7+
8+ ``` rb
9+ class TreeNode
10+ attr_accessor :data , :left , :right
11+
12+ def initialize (data )
13+ @data = data
14+ @left = nil
15+ @right = nil
16+ end
17+ end
18+
19+ class BinaryTree
20+ attr_accessor :root
21+
22+ def initialize (root_data )
23+ @root = TreeNode .new (root_data)
24+ end
25+
26+ def in_order_traversal (node = @root , result = [])
27+ return result unless node
28+
29+ in_order_traversal(node.left, result)
30+ result << node.data
31+ in_order_traversal(node.right, result)
32+ end
33+ end
34+
35+ # Usage:
36+ tree = BinaryTree .new (10 )
37+ tree.root.left = TreeNode .new (5 )
38+ tree.root.right = TreeNode .new (15 )
39+ tree.root.left.left = TreeNode .new (3 )
40+
41+ print tree.in_order_traversal # Output: [3, 5, 10, 15]
42+ ```
You can’t perform that action at this time.
0 commit comments