Class: DSAVisualizer::DataStructures::BinaryTree

Inherits:
Object
  • Object
show all
Defined in:
lib/dsa_visualizer/data_structures/binary_tree.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBinaryTree

Returns a new instance of BinaryTree.



16
17
18
# File 'lib/dsa_visualizer/data_structures/binary_tree.rb', line 16

def initialize
  @root = nil
end

Instance Attribute Details

#rootObject (readonly)

Returns the value of attribute root.



14
15
16
# File 'lib/dsa_visualizer/data_structures/binary_tree.rb', line 14

def root
  @root
end

Class Method Details

.demoObject



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.print_header("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

.learnObject



39
40
41
# File 'lib/dsa_visualizer/data_structures/binary_tree.rb', line 39

def self.learn
  demo
end

Instance Method Details

#insert(value) ⇒ Object



20
21
22
# File 'lib/dsa_visualizer/data_structures/binary_tree.rb', line 20

def insert(value)
  @root = insert_recursive(@root, value)
end