Skip to content

Commit

Permalink
Add RedBlackTree#include?
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuay03 committed Aug 7, 2024
1 parent 68b9463 commit 39a0377
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

- Alias `RedBlackTree#left_most_node` as `RedBlackTree#min`
- Add `RedBlackTree#search`
- Add `RedBlackTree#include?`

## [0.1.1] - 2024-08-04

Expand Down
8 changes: 8 additions & 0 deletions lib/red-black-tree.rb
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,14 @@ def search data
_search data, @root
end


# Returns true if there is a node which matches the given data/value, and false if there is not.
#
# @return [true, false]
def include? data
!!search(data)
end

private

# Rotates a (sub-)tree starting from the given node in the given direction.
Expand Down
32 changes: 32 additions & 0 deletions test/test_red_black_tree.rb
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,38 @@ def test_sub_tree_search
end
end

class TestInclude < Minitest::Test
def test_new_tree_include
tree = RedBlackTree.new
refute tree.include? 10
end

def test_single_node_tree_include
tree = RedBlackTree.new
node_10 = RedBlackTree::IntegerNode.new 10
tree << node_10
assert tree.include? 10
end

def test_sub_tree_include
tree = RedBlackTree.new
node_10 = RedBlackTree::IntegerNode.new 10
tree << node_10
node_5 = RedBlackTree::IntegerNode.new 5
tree << node_5
node_15 = RedBlackTree::IntegerNode.new 15
tree << node_15
node_1 = RedBlackTree::IntegerNode.new 1
tree << node_1
node_4 = RedBlackTree::IntegerNode.new 4
tree << node_4
assert tree.include? 5
assert tree.include? 15
tree.delete! node_5
refute tree.include? 5
end
end

class TestShift < Minitest::Test
def test_new_tree_shift
tree = RedBlackTree.new
Expand Down

0 comments on commit 39a0377

Please sign in to comment.