Back to Freecodecamp

Step 31

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

latest1.9 KB
Original Source

--description--

In the body of the __str__ method, delete pass and return the result of calling the str() function with self.key as the argument. This is the attribute of the current node object that stores the value associated with the node.

After returning the result, you should see the exception disappear from the console and the output should now display the value of the key associated with the node.

--hints--

You should remove the pass keyword from the __str__ method.

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

You should return the string value of self.key from your __str__ method.

js
({ test: () => assert.match(code, /^\s{8}return\s+str\(\s*self\.key\s*\)/m) })

--seed--

--seed-contents--

py

class TreeNode:

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

--fcc-editable-region--
    def __str__(self):
        pass

--fcc-editable-region--

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)
        
    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):
        return self._search(self.root, key)

bst = BinarySearchTree()

nodes = [50, 30, 20, 40, 70, 60, 80]

for node in nodes:
    bst.insert(node)

print('Search for 80:', bst.search(80))