Back to Freecodecamp

Step 11

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

latest1.0 KB
Original Source

--description--

Now you need to recursively traverse the tree and insert the values using the principle for binary trees:

  • Values smaller than the key are placed in the left subtree
  • Values greater than the key are placed in the right subtree

After your existing conditional statement, write another if statement to check if key is less than node.key.

--hints--

You should write another if statement to check if key is less than node.key. Remember to use the pass keyword.

js
({ test: () => assert(runPython(` _Node(_code).find_class("BinarySearchTree").find_function("_insert").find_ifs()[1].find_conditions()[0].is_equivalent("key < node.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
--fcc-editable-region--
    def _insert(self, node, key):
        if node is None:
            return TreeNode(key)

--fcc-editable-region--