1
+ module BinaryTree.BinarySearchTree where
2
+
3
+ data BTree a = Empty | Node a (BTree a ) (BTree a ) deriving (Show )
4
+ data Side = LeftSide | RightSide deriving (Eq , Show )
5
+
6
+ -- Function to get the data associated with the node.
7
+ nodeKey :: BTree a -> Maybe a
8
+ nodeKey Empty = Nothing
9
+ nodeKey (Node x _ _) = Just x
10
+
11
+ -- Perform inorder walk of the binary search tree.
12
+ -- Cormen, Thomas H., et al. Introduction to algorithms. pg. 288, MIT press, 2009.
13
+ inorderWalk :: (Eq a , Ord a ) => BTree a -> [a ]
14
+ inorderWalk Empty = []
15
+ inorderWalk (Node x l r) = (inorderWalk l) ++ [x] ++ (inorderWalk r)
16
+
17
+ -- Function to insert a value into the tree. Returns the new tree.
18
+ -- Cormen, Thomas H., et al. Introduction to algorithms. pg. 294, MIT press, 2009.
19
+ bstInsert :: (Eq a , Ord a ) => BTree a -> a -> BTree a
20
+ bstInsert Empty z = Node z Empty Empty
21
+ bstInsert (Node x l r) z
22
+ | z < x = Node x (bstInsert l z) r
23
+ | otherwise = Node x l (bstInsert r z)
24
+
25
+ -- Function to find the maximum value in the BST.
26
+ bstMax :: (Eq a , Ord a ) => BTree a -> Maybe a
27
+ bstMax Empty = Nothing
28
+ bstMax (Node x Empty Empty ) = Just x
29
+ bstMax (Node x l Empty ) = Just x
30
+ bstMax (Node x l r) = bstMax r
31
+
32
+ -- Function to find the minimum value in the BST.
33
+ bstMin :: (Eq a , Ord a ) => BTree a -> Maybe a
34
+ bstMin Empty = Nothing
35
+ bstMin (Node x Empty Empty ) = Just x
36
+ bstMin (Node x Empty r) = Just x
37
+ bstMin (Node x l r) = bstMin l
38
+
39
+ -- Function to build BST from a list of values using a fold.
40
+ bstFromList :: (Eq a , Ord a ) => [a ] -> BTree a
41
+ bstFromList [] = Empty
42
+ bstFromList lst = foldl (\ tree elem -> bstInsert tree elem ) Empty lst
43
+
44
+ sampleTree = bstFromList [10 , 7 , 3 , 11 , 12 , 1 , 3 , 2 ]
45
+
46
+ -- Function to check if a given tree is a Binary Search Tree.
47
+ -- Property:
48
+ -- x is a node in the BST. If y is a node in the left subtree of x then
49
+ -- y.key <= x.key. If y is a node in the right subtree of x then
50
+ -- y.key >= x.key.
51
+ -- Cormen, Thomas H., et al. Introduction to algorithms. MIT press, 2009.
52
+ isBST :: (Ord a , Eq a ) => BTree a -> Bool
53
+ isBST Empty = True
54
+ isBST (Node x Empty Empty ) = True
55
+ isBST (Node x Empty r) = (x < (nkey r)) && (isBST r) where nkey = (\ (Node n ll rr) -> n)
56
+ isBST (Node x l Empty ) = (x >= (nkey l)) && (isBST l) where nkey = (\ (Node n ll rr) -> n)
57
+ isBST (Node x l r) = (x >= (nkey l)) && (x < (nkey r)) && (isBST l) && (isBST r) where nkey = (\ (Node n ll rr) -> n)
0 commit comments