Back to Freecodecamp

Step 24

curriculum/challenges/english/blocks/learn-tree-traversal-by-building-a-binary-search-tree/65c63fd9b387f0a6c5bf6a72.md

latest2.1 KB
Original Source

--description--

Inside the search method, delete pass and call the helper method _search with the following arguments.

  • self.root: This is the root of the binary search tree. The search starts from the root.
  • key: This is the value that the user wants to find in the binary search tree.

Internally, search delegates the actual search logic to the _search helper method that performs the actual recursive search within the binary search tree.

--hints--

You should remove the pass keyword from the search method.

js
({
  test: () => {
    assert.isFalse(
      runPython(
        `_Node(_code).find_class("BinarySearchTree").find_function("search").has_pass()`
      )
    );
  },
});

You should call the _search method within the search method.

js
({ test: () => assert(runPython(`
  str(_Node(_code).find_class("BinarySearchTree").find_function("search").find_calls("_search")[0]).startswith("self._search(")
`)) });

You should call the _search method passing self.root and key as the arguments.

js
({ test: () => assert(runPython(`
  _Node(_code).find_class("BinarySearchTree").find_function("search").find_calls("_search")[0].is_equivalent("self._search(self.root, key)")
`)) });

--seed--

--seed-contents--

py

class TreeNode:

    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None


class BinarySearchTree:

    def __init__(self):
        self.root = None

    def _insert(self, node, key):
        if node is None:
            return TreeNode(key)

        if key < node.key:
            node.left = self._insert(node.left, key)
        elif key > node.key:

            node.right = self._insert(node.right, key)
        return node

    def insert(self, key):
        self.root = self._insert(self.root, key)
        
--fcc-editable-region--
    def _search(self, node, key):
        if node is None or node.key == key:
            return node
        if key < node.key:
            return self._search(node.left, key)
        return self._search(node.right, key)
    
    def search(self, key):
        pass
--fcc-editable-region--