Trees
Build a Binary Tree
Create a fixed seven-node binary tree and render its shape.
Algorithm
The canonical tree is 4(2(1,3),6(5,7)), so this Ruby DSA
implementation can be compared directly with the rest of the DSA track.
node links
A node stores one value plus references to its left and right children.
Basic Implementation
basic.rb
Replay: real traced execution (multi-file project)
class Node
attr_accessor :value, :left, :right
def initialize(value, left = nil, right = nil)
@value = value
@left = left
@right = right
end
end
def render(node)
return "_" if node.nil?
return node.value.to_s if node.left.nil? && node.right.nil?
"#{node.value}(#{render(node.left)},#{render(node.right)})"
end
def sample_tree
Node.new(4, Node.new(2, Node.new(1), Node.new(3)), Node.new(6, Node.new(5), Node.new(7)))
end
puts render(sample_tree)
node ← 1, tree ← 1
1class Node2 attr_accessor :value, :left, :rightvalues this step1node1treenode ← 3, tree ← 1, 3
1class Node2 attr_accessor :value, :left, :rightvalues this step3node1, 3treenode ← 2, tree ← 2(1,3)
1class Node2 attr_accessor :value, :left, :rightvalues this step2node2(1,3)treenode ← 5, tree ← 2(1,3), 5
1class Node2 attr_accessor :value, :left, :rightvalues this step5node2(1,3), 5treenode ← 7, tree ← 2(1,3), 5, 7
1class Node2 attr_accessor :value, :left, :rightvalues this step7node2(1,3), 5, 7treenode ← 6, tree ← 2(1,3), 6(5,7)
1class Node2 attr_accessor :value, :left, :rightvalues this step6node2(1,3), 6(5,7)treenode ← 4, tree ← 4(2(1,3),6(5,7))
1class Node2 attr_accessor :value, :left, :rightvalues this step4node4(2(1,3),6(5,7))treestdout ← 4(2(1,3),6(5,7))
1class Node2 attr_accessor :value, :left, :rightvalues this step4(2(1,3),6(5,7))stdout4(2(1,3),6(5,7))tree
Complexity
- Time: O(n)
- Space: O(n)
Implementation notes
Nodeis a Ruby class withattr_accessor :value, :left, :right, so each node stores one value and mutable child references.initialize(value, left = nil, right = nil)usesnilas the empty-child value.sample_treebuilds the whole tree with nestedNode.newcalls rather than later child assignments.- The root call is
Node.new(4, ..., ...); its left subtree is rooted at2and its right subtree is rooted at6. - The trace shows construction from leaves upward:
1,3, then2(1,3), followed by5,7, then6(5,7), and finally root4. render(node)printsnilas_, leaf nodes as their value, and internal nodes asvalue(left,right).puts render(sample_tree)prints the compact tree string4(2(1,3),6(5,7)).