-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.py
113 lines (78 loc) · 2.62 KB
/
tree.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
"""Tree class and tree node class."""
class Node(object):
"""Node in a tree."""
def __init__(self, data, children=None):
children = children or []
assert isinstance(children, list), \
"children must be a list!"
self.data = data
self.children = children
def __repr__(self):
"""Reader-friendly representation."""
return "<Node %s>" % self.data
def get_num_children(self):
"""Get number of children.
For example::
>>> a = Node("A", [Node("B"), Node("C")])
>>> a.get_num_children()
2
"""
return len(self.children)
class Tree(object):
"""Tree."""
def __init__(self, root):
self.root = root
def __repr__(self):
"""Reader-friendly representation."""
return "<Tree root=%s>" % self.root
def depth_first_search(self, data):
"""Return node object with this data, traversing the tree depth-first.
Start at the root, and return None if not found.
"""
to_visit = [self.root]
while to_visit:
node = to_visit.pop()
if node.data == data:
return node
to_visit.extend(node.children)
def breadth_first_search(self, data):
"""Return node object with this data, traversing the tree breadth-first.
Start here (on this node), and return None if not found.
Let's make a tree where we have two "B" nodes, but where one is far down an
earlier branch and the other is higher-up in an earlier branch. Since this is
a BFS, we should find the b2 node for "B"::
A
/ \
C E
/ \
D B2
/
B1
>>> a = Node("A")
>>> b1 = Node("B")
>>> b2 = Node("B")
>>> c = Node("C")
>>> d = Node("D")
>>> e = Node("E")
>>> a.children = [c, e]
>>> c.children = [d]
>>> d.children = [b1]
>>> e.children = [b2]
>>> tree = Tree(a)
>>> tree.depth_first_search("B") is b2
True
"""
to_visit = [self.root]
while to_visit:
node = to_visit.pop(0)
if node.data == data:
return node
else:
to_visit.extend[node.children]
if __name__ == "__main__":
import doctest
print
result = doctest.testmod()
if not result.failed:
print "ALL TESTS PASSED. GOOD WORK!"
print