Hackbright Code Challenges

Make Binary Search Tree

Make Binary Search Tree

Challenge

Medium

Concepts

Trees, Recursion

Download

make-bst.zip

Solution

Make Binary Search Tree: Solution


A binary search tree is a binary tree where all left-hand node values are less than or equal to the node value, and all right-hand node values are greater than the node value.

For example:

digraph bst { rankdir=TB 4-> 2; 4 -> NULLNULLNU [style=invis]; 4 -> 6; 2 -> 1; 2 -> X [style=invis]; 2 -> 3; 6 -> 5; 6 -> Y [style=invis]; 6 -> 7; NULLNULLNU [style=invis] X [style=invis] Y [style=invis] }

We’ve written a simple BinaryNode class for binary search tree nodes, with a data attribute and left and right child note attributes.

makebst.py
class BinaryNode(object):
    """Node in a binary tree."""

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

We’ve also provided the sub of a make_bst function:

makebst.py
def make_bst(nums):
    """Given a list of sorted numbers, make a binary search tree.

    Returns the root node of a new BST that is valid and balanced.
    """

When you run the makebst.py file, the tests do not pass. This is expected, as we haven’t implemented the make_bst function.

Your Task

Given a sorted Python list of integers, produce a balanced binary search tree from the list of integers.

For example, given the list nums = [1, 2, 3, 4, 5, 6, 7], you should produce the tree shown above.

If you can’t generate a perfectly-balanced tree, you should prefer to fill left-hand children over right-hand ones.

So, for example, nums = [1, 2, 3, 4] should give:

digraph bst2 { rankdir=TB 3-> 2; 2 -> 1; 2 -> X [style=invis]; 3 -> 4; X [style=invis] }

Implement the make_bst function.

Once you do this, all tests should pass.

Hint

How to Start

There’s a reason we’ve given you the list sorted.

Think about how binary search works—for the “guess a number between 1 and 100” game, you start in the middle, and move halfway up or down for each guess. Is there a way to take that same kind of thinking and apply it to building a binary search tree from a list?