-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterative_bst_validation.py
More file actions
57 lines (48 loc) · 1.78 KB
/
iterative_bst_validation.py
File metadata and controls
57 lines (48 loc) · 1.78 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
# Collections module has already been imported.
class TreeNode:
def __init__(self, data, left_child=None, right_child=None):
self.data = data
self.left_child = left_child
self.right_child = right_child
class Stack:
def __init__(self):
self.storage = []
self.size = 0
def push(self, data):
self.size += 1
self.storage.append(data)
def pop(self):
self.size -= 1
return self.storage.pop()
class BinaryTree:
def __init__(self, root_node=None):
self.root = root_node
def validate_BST_Itr(self, root):
# Return type should be Boolean
stack = Stack()
stack.push(root)
while stack.size > 0:
current = stack.pop()
if current.left_child is not None and current.right_child is not None:
if current.data < root.data:
if current.left_child.data > root.data or current.right_child.data > root.data:
return False
if current.data > root.data:
if current.left_child.data < root.data or current.right_child.data < root.data:
return False
if current.right_child is not None:
if current.right_child.data > current.data:
stack.push(current.right_child)
else:
return False
if current.left_child is not None:
if current.left_child.data < current.data:
stack.push(current.left_child)
else:
return False
return True
test_root = TreeNode(10)
test_root.left_child = TreeNode(5)
test_root.right_child = TreeNode(15)
test_bst = BinaryTree(test_root)
test_bst.validate_BST_Itr(test_root)