-
Notifications
You must be signed in to change notification settings - Fork 3
/
binary_search_tree_validator.py
79 lines (56 loc) · 1.71 KB
/
binary_search_tree_validator.py
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
73
74
75
76
77
78
79
"""Is this binary search tree a valid BST?
A valid binary search tree follows a specific rule. In our case,
the rule is "left child must value must be less-than parent-value"
and "right child must be greater-than-parent value".
This rule is recursive, so *everything* left of a parent
must less than that parent (even grandchildren or deeper)
and everything right of a parent must be greater than.
For example, this tree is valid::
4
2 6
1 3 5 7
Let's create this tree and test that::
>>> t = Node(4,
... Node(2, Node(1), Node(3)),
... Node(6, Node(5), Node(7))
... )
>>> t.is_valid()
True
This tree isn't valid, as the left-hand 3 is wrong (it's less
than 2)::
4
2 6
3 3 5 7
Let's make sure that gets caught::
>>> t = Node(4,
... Node(2, Node(3), Node(3)),
... Node(6, Node(5), Node(7))
... )
>>> t.is_valid()
False
This tree is invalid, as the bottom-right 1 is wrong --- it is
less than its parent, 6, but it's also less than its grandparent,
4, and therefore should be left of 4::
4
2 6
1 3 1 7
>>> t = Node(4,
... Node(2, Node(1), Node(3)),
... Node(6, Node(1), Node(7))
... )
>>> t.is_valid()
False
"""
class Node:
"""Binary search tree node."""
def __init__(self, data, left=None, right=None):
"""Create node, with data and optional left/right."""
self.left = left
self.right = right
self.data = data
def is_valid(self):
"""Is this tree a valid BST?"""
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED; THAT'S VALID!\n"