Trees
BST Search
Search a binary search tree for one present and one absent value.
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.
Basic Implementation
basic.rb
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
def search(root, target); node = root; until node.nil?; return true if target == node.value; node = target < node.value ? node.left : node.right; end; false; end
root = sample_tree
puts(search(root, 5) ? '5 found' : '5 not found')
puts(search(root, 8) ? '8 found' : '8 not found')
Complexity
- Time: O(h) per search
- Space: O(1) iterative
Implementation notes
- Render tree structure explicitly instead of printing node objects.
- The replay highlights the node, traversal state, queue, path, or search cursor that changes at each step.
search path
A comparison chooses one subtree at each step, so whole branches are skipped.