-
-
Notifications
You must be signed in to change notification settings - Fork 50.3k
Expand file tree
/
Copy pathtree.py
More file actions
84 lines (73 loc) · 1.86 KB
/
tree.py
File metadata and controls
84 lines (73 loc) · 1.86 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
73
74
75
76
77
78
79
80
81
82
83
84
class Node:
def __init__(self, info: int) -> None:
self.info = info
self.left: Node | None = None
self.right: Node | None = None
def __str__(self) -> str:
"""
>>> str(Node(5))
'5'
"""
return str(self.info)
class BinarySearchTree:
def __init__(self) -> None:
self.root: Node | None = None
def create(self, val: int) -> None:
"""
>>> bst = BinarySearchTree()
>>> bst.create(10)
>>> bst.root.info
10
>>> bst.create(5)
>>> bst.root.left.info
5
"""
if self.root is None:
self.root = Node(val)
else:
current = self.root
while True:
if val < current.info:
if current.left:
current = current.left
else:
current.left = Node(val)
break
elif val > current.info:
if current.right:
current = current.right
else:
current.right = Node(val)
break
else:
break
def height(node: Node | None) -> int:
"""
>>> height(None)
-1
>>> n = Node(3)
>>> height(n)
0
>>> n.left = Node(2)
>>> n.right = Node(5)
>>> n.right.right = Node(6)
>>> height(n)
2
"""
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
def tree_height_from_list(data: list[int]) -> int:
"""
>>> tree_height_from_list([3,2,5,6])
2
>>> tree_height_from_list([1])
0
"""
bst = BinarySearchTree()
for x in data:
bst.create(x)
return height(bst.root)
if __name__ == "__main__":
import doctest
doctest.testmod()