Browse Source

Code for 01 mar.

Abhinav Sarkar 4 years ago
parent
commit
8a8f3714d0
1 changed files with 32 additions and 0 deletions
  1. 32
    0
      2016-03-01/BST.hs

+ 32
- 0
2016-03-01/BST.hs View File

@@ -0,0 +1,32 @@
1
+module BST where
2
+
3
+data BST = EmptyNode | Node BST Int BST deriving (Show, Eq)
4
+
5
+inOrder :: BST -> [Int]
6
+inOrder EmptyNode    = []
7
+inOrder (Node l v r) = inOrder l ++ [v] ++ inOrder r
8
+
9
+find :: BST -> Int -> Bool
10
+find EmptyNode _ = False
11
+find (Node l v r) x
12
+  | x == v    = True
13
+  | x > v     = find r x
14
+  | otherwise = find l x
15
+
16
+insert :: BST -> Int -> BST
17
+insert EmptyNode x = Node EmptyNode x EmptyNode
18
+insert node@(Node left value right) x
19
+  | x < value = Node (insert left x) value right
20
+  | x > value = Node left value (insert right x)
21
+  | otherwise = node
22
+
23
+fromList :: [Int] -> BST
24
+fromList []       = EmptyNode
25
+fromList (first : rest) = insert (fromList rest) first
26
+
27
+isBST :: BST -> Bool
28
+isBST EmptyNode = True
29
+isBST (Node EmptyNode _ EmptyNode) = True
30
+isBST (Node l@(Node _ lv _) v EmptyNode) = lv < v && isBST l
31
+isBST (Node EmptyNode v r@(Node _ rv _)) = rv > v && isBST r
32
+isBST (Node l@(Node _ lv _) v r@(Node _ rv _)) = lv < v && v > rv && isBST l && isBST r

Loading…
Cancel
Save