Skip to content

Instantly share code, notes, and snippets.

@andrewpurcell
Created December 21, 2012 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewpurcell/4351007 to your computer and use it in GitHub Desktop.
Save andrewpurcell/4351007 to your computer and use it in GitHub Desktop.
"interview practice" solution for problem: write a function that validates a binary tree
require 'test/unit'
class Node
attr_accessor :val, :left, :right
def initialize val
@val = val
end
def >(other)
@val > other.val
end
def <(other)
@val < other.val
end
end
def validate_tree root
if root.nil?
return true
elsif root.left.nil?
return true if root.right.nil?
return false if root > root.right
elsif root.right.nil?
return false if root < root.left
end
return false if root.left > root.right ||
root.left > root ||
root > root.right
return false unless validate_tree(root.left)
return false unless validate_tree(root.right)
true
end
class BinaryTreeValidatorTest < Test::Unit::TestCase
def test_base_case
root = Node.new 7
root.left = Node.new 8
root.right = Node.new 9
assert !validate_tree(root), "Tree is invalid but validate returns true"
end
def test_fails_for_invalid_trees
root = Node.new 7
root.left = Node.new 4
root.right = Node.new 8
root.left.left = Node.new 5
assert !validate_tree(root), "Tree is invalid and not complete, but validate returns true"
end
def test_passes_for_valid_trees
root = Node.new 5
root.left = Node.new 4
root.right = Node.new 6
assert validate_tree(root), "Valid tree returns invalid"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment