Back to Freecodecamp

Step 20

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

latest1.8 KB
Original Source

--description--

Now you are going to define a base case for the recursive search. Remove the current pass and write an if statement that checks two conditions:

  • If node is None: This indicates that the search has reached the end of a branch without finding the key.
  • If node.key == key: This means that the key has been found in the current node.

Combine the two conditions with the or operator and return the current node inside the if block.

--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 write an if statement that checks if node is None or if node.key is equal to key.

js
({ test: () => assert.match(code, /^\s{8}if\s+node\s+is\s+None\s+or\s+node\.key\s*==\s*key\s*:/m) })

You should return node from the if block.

js
({ test: () => assert.match(code, /^(\s{8})if\s+node\s+is\s+None\s+or\s+node\.key\s*==\s*key\s*:\s*^\1\s{4}return\s+node/m) })

--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):
        pass

--fcc-editable-region--