Back to Freecodecamp

Step 21

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

latest1.5 KB
Original Source

--description--

Write another if statement that checks if the target key is less than the key of the current node.

Inside the if block, return the result of calling the _search method with the left child of the current node and key as the arguments.

--hints--

You should write another if statement to check if key < node.key.

js
({ test: () => assert(runPython(`_Node(_code).find_class("BinarySearchTree").find_function("_search").find_ifs()[1].find_conditions()[0].is_equivalent("key < node.key")`)) })

You should return self._search(node.left, key) from your new if block.

js
({ test: () => assert(runPython(`_Node(_code).find_class("BinarySearchTree").find_function("_search").find_ifs()[1].find_bodies()[0].is_equivalent("return self._search(node.left, 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

--fcc-editable-region--