Binary Search Trees

Agenda

  • Binary Trees & Binary Search Trees: definitions
  • Linked tree structure and Manual construction
  • Recursive binary search tree functions

Binary Tree: def

  • A binary tree is a structure that is either empty, or consists of a root node containing a value and references to a left and right sub-tree, which are themselves binary trees.

Binary Search Tree (BSTree): def

  • A binary search tree is a binary tree where the value contained in every node is:
    • greater than all keys in its left subtree, and
    • less than all keys in its right subtree

Linked tree structure and Manual construction:

In [ ]:
class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
In [ ]:
t = None
In [ ]:
t = Node(10)
In [ ]:
t = Node(10, left=Node(5), right=Node(15))
In [53]:
t = Node(10,
        left=Node(5,
                 left=Node(-100),
                 right=Node(7,
                           left=Node(6))),
         right=Node(30,
                   left=Node(20,
                            right=Node(25))))
In [ ]:
t.left.right.left.val
In [ ]:
t.right.left.right.val

Recursive bstree functions

In [52]:
def min(t):
    if not t.left:
        return t.val
    else:
        return min(t.left)
In [54]:
min(t)
Out[54]:
-100
In [55]:
def max(t):
    if not t.right:
        return t.val
    else:
        return max(t.right)
In [56]:
max(t)
Out[56]:
30
In [61]:
def find(t, x):
    if t:
        print(t.val)
    if not t:
        return False
    elif t.val == x:
        return True
    elif t.val < x:
        return find(t.right, x)
    else: #t.val > x
        return find(t.left, x)
In [63]:
find(t, -100)
10
5
-100
Out[63]:
True
In [67]:
def traverse(t, fn):
    if t: #there are still nodes in the tree
        traverse(t.left, fn)
        traverse(t.right, fn)
        fn(t.val)
In [68]:
traverse(t, print)
-100
6
7
5
25
20
30
10