10
, 12
, 17
, 25
。根据我们的规则二叉搜索树,我们将增加12
到右侧10
, 17
,以这样的权利,以及25
到这一权利。现在我们的树类似于一个链表,并且遍历它以找到25
将要求我们以线性方式遍历所有项目。因此,在最坏的情况下,线性时间。这里的问题是树是不平衡的。我们将更多地了解这在以下挑战中意味着什么。说明:在此挑战中,我们将为树创建一个实用程序。编写一个方法isPresent
,它接受一个整数值作为输入,并在二叉搜索树中返回该值是否存在的布尔值。 BinarySearchTree
数据结构。
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() }; return (typeof test == "object")})(), "The BinarySearchTree
data structure exists.");'
- text: 二叉搜索树有一个名为isPresent
的方法。
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; return (typeof test.isPresent == "function")})(), "The binary search tree has a method called isPresent
.");'
- text: isPresent
方法正确检查添加到树中的元素是否存在。
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.isPresent !== "function") { return false; }; test.add(4); test.add(7); test.add(411); test.add(452); return ( test.isPresent(452) && test.isPresent(411) && test.isPresent(7) && !test.isPresent(100) ); })(), "The isPresent
method correctly checks for the presence or absence of elements added to the tree.");'
- text: isPresent
处理树为空的情况。
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== "undefined") { test = new BinarySearchTree() } else { return false; }; if (typeof test.isPresent !== "function") { return false; }; return test.isPresent(5) == false; })(), "isPresent
handles cases where the tree is empty.");'
```