Last active
August 28, 2018 08:37
-
-
Save woodRock/6fbf7e760ff0099f083ee43f4cede0f4 to your computer and use it in GitHub Desktop.
Implement locking in a binary tree. A binary tree node can be locked or unlocked only if all of its descendants or ancestors are not locked. Design a binary tree node class with the following methods: is_locked, which returns whether the node is locked lock, which attempts to lock the node. If it cannot be locked, then it should return false. Ot…
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
class BinaryTreeLock | |
attr_accessor :locked, :left, :right | |
def initialize(left=nil, right=nil, unlocked) | |
@left = left | |
@right = right | |
@unlocked = unlocked | |
end | |
def lock | |
if is_unlocked() && @unlocked | |
@locked = true | |
return true | |
end | |
return false | |
end | |
def unlock | |
if is_unlocked() && !@unlocked | |
@locked = false | |
return true | |
end | |
return false | |
end | |
def is_unlocked | |
res = true | |
if @left.nil? && @right.nil? | |
return @unlocked | |
end | |
if [email protected]? | |
res &= @left.is_unlocked() | |
end | |
if [email protected]? | |
res &= @right.is_unlocked() | |
end | |
return res | |
end | |
end | |
class Assertion | |
attr_accessor :root, :expected, :msg | |
def initialize(root, expected, msg="") | |
@root = root | |
@expected = expected | |
@msg = msg | |
end | |
end | |
def test | |
test = Array.new | |
test << Assertion.new(BinaryTreeLock.new(unlocked = true), true, msg="One unlocked node") | |
test << Assertion.new(BinaryTreeLock.new(unlocked = false), false, msg="One locked node") | |
test << Assertion.new(BinaryTreeLock.new(left=BinaryTreeLock.new(unlocked=true), right=BinaryTreeLock.new(unlocked=true), unlocked=true), true, msg="Root with two children, all unlocked") | |
test << Assertion.new(BinaryTreeLock.new(left=BinaryTreeLock.new(unlocked=false), right=BinaryTreeLock.new(unlocked=true), unlocked=true), false, msg="Root with two children, left is locked, right is unlocked") | |
test << Assertion.new(BinaryTreeLock.new(left=BinaryTreeLock.new(unlocked=true), right=BinaryTreeLock.new(unlocked=false), unlocked=true), false, msg="Root with two children, left is unlocked, right is locked") | |
test.each do |t| | |
puts "#{t.msg}:\n#{t.root.is_unlocked()==t.expected()}" | |
end | |
end | |
if __FILE__ == $0 | |
test() | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment