43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
# File 'lib/dsa_visualizer/data_structures/binary_tree.rb', line 43
def self.demo
Visualizer.("BINARY SEARCH TREE - Core Level Visualization")
Visualizer.print_section("1. BST Concept")
puts "\nBinary Search Tree properties:"
puts " - Left subtree < node < right subtree"
puts " - Enables O(log n) search in balanced tree"
puts " - Can degrade to O(n) if unbalanced"
Visualizer.print_section("2. Implementation Comparison")
ruby_code = <<~RUBY
class TreeNode
attr_accessor :value, :left, :right
def initialize(value)
@value = value
@left = @right = nil
end
end
# Ruby: object references for children
# GC handles memory
RUBY
cpp_code = <<~CPP
struct TreeNode {
int value;
TreeNode *left, *right;
TreeNode(int v) : value(v),
left(nullptr), right(nullptr) {}
};
// C++: explicit pointers
// Manual memory management
CPP
explanation = "Both use pointer-based structure. Ruby uses object references with GC, C++ uses raw pointers requiring manual deletion. Tree traversal is same in both."
Visualizer.print_comparison(ruby_code, cpp_code, explanation)
tree = BinaryTree.new
values = [50, 30, 70, 20, 40, 60, 80]
Visualizer.print_step(1, "Inserting values: #{values.join(', ')}")
values.each { |v| tree.insert(v) }
puts "\nTree structure:"
puts " 50"
puts " / \\"
puts " 30 70"
puts " / \\ / \\"
puts " 20 40 60 80"
puts "\n\nšÆ Key Takeaways:".colorize(:green).bold
puts " 1. BST enables efficient searching: O(log n) average"
puts " 2. Insertion/deletion: O(log n) average"
puts " 3. Worst case O(n) for unbalanced tree"
puts " 4. Self-balancing trees (AVL, Red-Black) maintain O(log n)"
end
|