Created
December 21, 2012 06:20
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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