-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path4.5.check_bst.py
More file actions
72 lines (58 loc) · 1.31 KB
/
Copy path4.5.check_bst.py
File metadata and controls
72 lines (58 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# 10:02
class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def add(self, node=None):
if node is None:
return False
if self.root is None:
self.root = node
return self.root
temp = self.root
while temp:
if node.data <= temp.data:
if temp.left is None:
temp.left = node
return True
else:
temp = temp.left
else:
if temp.right is None:
temp.right = node
return True
else:
temp = temp.right
return False
def isBST(root=None):
if root is None:
return True
treeNodes = []
inOrder(root, treeNodes)
return checkIncrease(treeNodes)
def checkIncrease(array):
for i in range(1, len(array)):
if array[i-1] > array[i]:
return False
return True
def inOrder(root=None, outputs=[]):
if root is None:
return None
inOrder(root.left, outputs)
outputs.append(root.data)
inOrder(root.right, outputs)
if __name__ == '__main__':
tree = Tree()
tree.add(Node(2))
tree.add(Node(1))
tree.add(Node(3))
tree2 = Tree()
tree2.root = Node(11)
tree2.root.left = Node(55)
tree2.root.right = Node(1111)
print isBST(tree.root)
print isBST(tree2.root)