From 92d212967d2a4b61231bf98c3820a35ed826123b Mon Sep 17 00:00:00 2001 From: Joshua Young Date: Wed, 7 Aug 2024 20:47:03 +0530 Subject: [PATCH] add RedBlackTree#include? --- CHANGELOG.md | 1 + lib/red-black-tree.rb | 7 +++++++ test/test_red_black_tree.rb | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 611a721..9510a83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ - Alias `RedBlackTree#left_most_node` as `RedBlackTree#min` - Add `RedBlackTree#search` +- Add `RedBlackTree#include?` ## [0.1.1] - 2024-08-04 diff --git a/lib/red-black-tree.rb b/lib/red-black-tree.rb index ce9f29a..c1f9008 100644 --- a/lib/red-black-tree.rb +++ b/lib/red-black-tree.rb @@ -229,6 +229,13 @@ 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. diff --git a/test/test_red_black_tree.rb b/test/test_red_black_tree.rb index a9bf207..7199821 100644 --- a/test/test_red_black_tree.rb +++ b/test/test_red_black_tree.rb @@ -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