-
Notifications
You must be signed in to change notification settings - Fork 34
/
ws2.py
56 lines (41 loc) · 1.23 KB
/
ws2.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
from collections import defaultdict
class DrawTree(object):
def __init__(self, tree, depth=-1):
self.x = -1
self.y = depth
self.tree = tree
self.children = [DrawTree(t) for t in tree]
self.thread = None
self.offset = 0
def layout(tree):
dt = DrawTree(tree)
setup(dt)
addmods(dt)
return dt
def setup(tree, depth=0, nexts=None, offset=None):
if nexts is None:
nexts = defaultdict(lambda: 0)
if offset is None:
offset = defaultdict(lambda: 0)
for c in tree.children:
setup(c, depth + 1, nexts, offset)
tree.y = depth
if not len(tree.children):
place = nexts[depth]
tree.x = place
elif len(tree.children) == 1:
place = tree.children[0].x - 1
else:
s = tree.children[0].x + tree.children[1].x
print(tree.children[0].x, tree.children[1].x, tree.tree)
place = s / 2
offset[depth] = max(offset[depth], nexts[depth] - place)
if len(tree.children):
tree.x = place + offset[depth]
nexts[depth] += 2
tree.offset = offset[depth]
def addmods(tree, modsum=0):
tree.x = tree.x + modsum
modsum += tree.offset
for t in tree.children:
addmods(t, modsum)