Skip to content

Commit 88fcb81

Browse files
committed
Add Ruby snippet for implementing a basic binary tree with in-order traversal
1 parent cdbd348 commit 88fcb81

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
```

0 commit comments

Comments
 (0)