Created
April 25, 2012 00:03
-
-
Save awagner83/2484753 to your computer and use it in GitHub Desktop.
Using reduce to build a binary search tree in python (& haskell)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data Tree a = Empty | |
| Node a (Tree a) (Tree a) | |
deriving (Show) | |
-- | Add a value to our binary search tree. (Hard work is done here) | |
addValue :: Ord a => Tree a -> a -> Tree a | |
addValue t@(Node v left right) x | |
| x < v = Node v (addValue left x) right | |
| x > v = Node v left (addValue right x) | |
| otherwise = t | |
addValue Empty x = Node x Empty Empty | |
-- | Generate a tree from a given list of values | |
buildTree :: Ord a => [a] -> Tree a | |
buildTree = foldl addValue Empty | |
-- | Now let's see it in action! | |
main = print $ buildTree [13, 3, 7, 23, 76, 23, 32] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Tree(object): | |
def __init__(self, val=None): | |
self.value = val | |
self.left = None | |
self.right = None | |
def add(self, val): | |
"""Add a value to the tree. | |
This is where all the hard work is done. | |
""" | |
if not self.value: | |
self.value = val | |
self.left = Tree() | |
self.right = Tree() | |
elif val < self.value: | |
self.left.add(val) | |
elif val > self.value: | |
self.right.add(val) | |
return self | |
def to_dict(self): | |
"""Not really a part of the implementation, just used to show that it | |
worked (when we pprint below).""" | |
return {'value': self.value, | |
'right': self.right.to_dict() if self.right else None, | |
'left': self.left.to_dict() if self.left else None} | |
def insert_into_tree(tree, number): | |
return tree.add(number) | |
def build_tree(numbers): | |
return reduce(insert_into_tree, numbers, Tree()) | |
numbers = [13, 3, 7, 23, 76, 23, 32] | |
tree = build_tree(numbers) | |
# Now let's see what it looks like | |
from pprint import pprint | |
pprint(tree.to_dict()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment